0

Hey guys is there a way i can retrieve the last unique object in an array in the code below the id at the first and second index are the same is there a way i can retrieve the last occurrence of the id with the corresponding object

0: {id: 'tra.528555295', name: 'heart'}
1: {id: 'tra.528555295', name: 'heart-outline'}
2: {id: 'tra.528555301', name: 'heart'}
3: {id: 'tra.528555301', name: 'heart-outline'}
2
  • What is the expected output? Commented Jan 23, 2022 at 13:06
  • @goto i just need the object where the similar id's occurs last in the array like in the code i gave the object at index 1 and index 3 should be returned Commented Jan 23, 2022 at 13:10

2 Answers 2

3

You need to iterate through the entire array and keep track of the "last" object with that unique ID found.

Here's one way you can do it using Array.prototype.reduce to iterate through the array and keep track of the "last" ID found, then pulling values with unique IDs using Object.values:

const arr = [
  { id: "tra.528555295", name: "heart" },
  { id: "tra.528555295", name: "heart-outline" },
  { id: "tra.528555301", name: "heart" },
  { id: "tra.528555301", name: "heart-outline" }
];

const result = Object.values(
  arr.reduce((accumulator, item) => {
    const { id, ...rest } = item;
    return {
      ...accumulator,
      [id]: { id, ...rest }
    };
  }, {})
);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

If you can provide the id I suggest:

const findLastElementOfId = (arr, id) => {
    return arr.filter(object => object.id === id).at(-1)
}

filter the array for the objects with the id you are looking for and return the last one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.