Home > Back-end >  how to retrieve the last unique object in an array
how to retrieve the last unique object in an array

Time:01-24

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'}

CodePudding user response:

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);

CodePudding user response:

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.

  •  Tags:  
  • Related