Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

46
Vistas
how to retrieve the last unique object in an array

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'}
7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

7 months ago · Juan Pablo Isaza Denunciar

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.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos