Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
How to compare two arrays and return another one?

How to compare two arrays and return another one? I'm trying to compare two arrays to compare records by id and then render a new array

const arr1 = [
  { id: 1, title: "Admin" },
  { id: 2, title: "Vip" }
];

const arr2 = [
  {
    id: 1,
    root: 1
  },
  {
    id: 2,
    root: 0
  }
];

let intersection = arr1.filter(({ id }) => arr2.includes(id));

need:

const needArr = [
  { id: 1, title: "Admin", root: 1 },
  { id: 2, title: "Vip", root: 0 }
];
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could make use of map() and find() and iterate over the first array arr1:

const needArr = arr1.map(entry => {
    const root = arr2.find(arr2Entry => entry.id === arr2Entry.id)?.root
    return {...entry, root: root}
} )

The root property will be set to undefined for each entry in the needArr result if there is no entry with the same id in arr2 as in arr1.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Something like this could work,


const giveNew = (a, b) => {
    let shorter, longer;
    if(a.length>b.length){
      longer = a;
      shorter = b;
    } else {
      longer = b;
      shorter = a;
    }
  
    return longer.map((v, i)=> {
      const matched = shorter.find(val=> val.id === v.id);
      if(matched){
          return {
          ...v, ...matched
      }
    }
  })
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming there's a 1:1 relationship between the arrays - map over one of the arrays, find the corresponding object in the other array by its id, and then return a new updated object.

const arr1=[{id:1,title:"Admin"},{id:2,title:"Vip"}],arr2=[{id:1,root:1},{id:2,root:0}];

const out = arr2.map(obj => {
  return {
    ...arr1.find(inner => inner.id === obj.id),
    root: obj.root
  };
});

console.log(out);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda