Remove and update an array without mutation in Javascript

Viewed 771

I have an array :

let originalArr = ['apple', 'plum', 'berry'];

How can I remove "plum" from this array without mutating the originalArr?

I can think of below approach :

let copyArr = [...originalArr];
originalArr = copyArr.filter(item => {
     return item !== 'plum';
});
2 Answers

You're creating two additional arrays: one copyArr and one filtered array. There's no need for both, creating just the filtered array should work fine, eg:

setOriginalArr(
  originalArr.filter(item => item !== 'plum')
);

as an example, if originalArr is in state.

Calling .filter on an array doesn't mutate the array it was called on - it returns a new, separate array, so it's safe to use in React without cloning the original array beforehand.

You can use slice() method to extract items from/to specific indexes (without mutation of original array)

let originalArr = ['apple', 'plum', 'berry'];
let sliced = originalArr.slice(1, 2)
console.log(originalArr, sliced)

Related