Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  18] [ 2]  / answers: 1 / hits: 32322  / 7 Years ago, mon, october 30, 2017, 12:00:00

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?


More From » arrays

 Answers
12

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




[#56059] Friday, October 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;