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

Daniel Santos picture Daniel Santos · Oct 30, 2017 · Viewed 17.5k times · Source

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?

Answer

Ori Drori picture Ori Drori · Oct 30, 2017

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);