Hi this question needed to be deleted
Asked
Active
Viewed 5,585 times
5
-
1use `filter` . but what you have tried so far ? – Code Maniac Dec 18 '18 at 12:45
-
1`Array.filter()` creates a new array with all the elements removed that return false on the filter function. Removing an item inside the array, by mutating it, can be done with `Array.splice()`. – Shilly Dec 18 '18 at 12:46
-
Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – SimoV8 Dec 18 '18 at 13:33
-
@SimoV8, that question isn't about immutable changes – AnonymousSB Dec 18 '18 at 16:36
2 Answers
18
You could use filter
or reduce
, or copy the array first by using slice
, and then perform splice
.
Personally, I like filter
for its simplicity, and clear intention
filter
function removeItem(array, n) {
return array.filter((elem, i) => i !== n);
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
reduce
function removeItem (array, n) {
return array.reduce((result, elem, i) => {
if (i !== n) result.push(elem);
return result;
}, [])
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
slice and splice
function removeItem(array, n) {
const result = array.slice();
result.splice(n, 1);
return result;
}
const original = [1,2,3,4];
console.log(removeItem(original, 1));
console.log(original);
Performance Test
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

AnonymousSB
- 3,516
- 10
- 28