Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to remove an element from an immutable array in JS? [duplicate]

I need to remove an element from an array that is a state of a React Component. Which means that it is an immutable object.

Adding a element is easy using spread syntax.

    return {         ...state,         locations: [...state.locations, {}]     }; 

Removing is a little more tricky. I need to use an intermediate object.

        var l = [...state.locations]         l.splice(index, 1)         return {             ...state,             locations: l         } 

It make the code more dirt and difficult to understand.

Is there an easier or less tricky to create a new array removing an element from it?

like image 747
Daniel Santos Avatar asked Oct 30 '17 20:10

Daniel Santos


People also ask

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How do you remove duplicates in array of objects in JS?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you remove an element from an array in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


1 Answers

You can use a combination of spread and Array#slice:

const arr = ['a', 'b', 'c', 'd', 'e'];    const indexToRemove = 2; // the 'c'    const result = [...arr.slice(0, indexToRemove), ...arr.slice(indexToRemove + 1)];    console.log(result);

Another option is Array#filter:

const arr = ['a', 'b', 'c', 'd', 'e'];    const indexToRemove = 2; // the 'c'    const result = arr.filter((_, i) => i !== indexToRemove);    console.log(result);
like image 115
Ori Drori Avatar answered Sep 23 '22 13:09

Ori Drori