Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove n from an array without mutating it?

Tags:

javascript

Hi this question needed to be deleted

like image 302
Geo Avatar asked Dec 18 '18 12:12

Geo


2 Answers

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

https://jsperf.com/so53833297

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

like image 82
AnonymousSB Avatar answered Oct 16 '22 20:10

AnonymousSB


function removeItem(array, n) {
    return array.filter((x, i) => i != n)
}
like image 24
Max Avatar answered Oct 16 '22 21:10

Max