Skip to content
Advertisement

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 }
];

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement