Hi this question needed to be deleted
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
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);
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);
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);
https://jsperf.com/so53833297
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
function removeItem(array, n) {
return array.filter((x, i) => i != n)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With