Skip to content
Advertisement

Compare and update two arrays without losing mutated data

I have an array of objects contains data of persons

const oldArr = [
    {
        id: 1,
        name: 'Alex',
    },
    {
        id: 2,
        name: 'John',
    },
    {
        id: 3,
        name: 'Jack',
    }
]

then I add data to this array to each element where I end up with new key called money with value of 20 as the following

oldArr.map((el, index) => el.money = 20)

and the array becomes like this

...
{
   id: 2,
   name: 'John',
   money: 20
},
...

Now, I have a new array with new data (new person) but missing the money I have added before. (careful person with id 2 is not there)

const newArr = [
    {
        id: 1,
        name: 'Alex',
    },
    {
        id: 3,
        name: 'Jack',
    },
    {
        id: 4,
        name: 'Chris',
    },
]

I want to update the old array with new data but also keep the mutated data, and I want the result to end up like this:

const result = [
    {
        id: 1,
        name: 'Alex',
        money: 20
    },
    {
        id: 3,
        name: 'Jack',
        money: 20
    },
    {
        id: 4,
        name: 'Chris',
    },
]

Thanks for the help.

Advertisement

Answer

Just a note: map creates a whole new array, it doesn’t make sense to use it for just mutating the contents. Use forEach or just a regular for loop instead.

oldArr.forEach((el) => (el.money = 20));

The following will give you the intended result:

const result = newArr.map(
  (newEl) => oldArr.find((el) => el.id === newEl.id) || newEl
);

The OR operator || returns the second argument if the first is falsey.


You can optimize this by mapping items by id instead of brute force searching the old array.

const idMap = new Map();
oldArr.forEach((el) => {
  el.money = 20;
  idMap.set(el.id, el);
});
const result = newArr.map((newEl) => idMap.get(newEl.id) || newEl);

Stackblitz: https://stackblitz.com/edit/js-f3sw8w?file=index.js

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