0

I have an array of objects like this:

const myArr = [{id: 1, ...}, {id: 2, ...}, {id: 3, ...}];

and I have an object like this:

const myObj: {id: 2, someNewField};

I want to replace this new object for the one with the same ID in the original array, how can I do this?

I tried doing it like this:

const index = myArr.findIndex(item => item.id === myObj.id);
const filteredArr = myArr.filter(item => item.id !== myObj.id);

filteredArr.splice(index, 0, myObj);

It works but maybe there's a better way to do it

3
  • 4
    If you are wanting to replace it, find the index of where the old one is and then simply myArr[theIndex] = <new object> Commented Dec 9, 2020 at 15:25
  • 1
    You're already using splice, there's no need to create a filtered version beforehand. E.g. myArr .splice(index, 1, myObj); Commented Dec 9, 2020 at 15:26
  • myArr.map((val) => val.id === myObj.id ? myObj : val) Commented Dec 9, 2020 at 15:29

2 Answers 2

2

Instead of finding the index and filtering you could always use .map to return a new array.

const myObj = { id: 2, new: 1 };
const myArr = [{ id: 1 }, { id: 2 }, { id: 3 }];

const newArr = myArr.map(v => {
    return v.id === myObj.id ? myObj : v;
});

It depends on what you would like to do if the item is not found in the array, as this will only replace.

Sign up to request clarification or add additional context in comments.

Comments

1

By better if you mean faster method, here is one,

for(let i = 0;i<myArr.length; i++) {
    if(myArr[i].id === myObj.id) {
        myArr[i] = myObj;
        break;
    }
}

This is faster than your method because we are using for loop instead of .filter() or .findIndex() which is slower than regular for loop.

If you mean the most compact then you can do this,

myArr[myArr.findIndex(item => item.id === myObj.id)] = myObj;

Note that this approach will fail if there is no item with the given object key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.