Bazinga
Bazinga

Reputation: 11224

Js remove element from array without change the original

I want to know if there is a way to do this without make a full copy of the array and then splice the copy.

var arr = [{id:1, name:'name'},{id:2, name:'name'},{id:3, name:'name'}];

I need to temp remove element by his index and use the array without this element, but i dont want to change the original array.

You can give me way even with lodash.

Upvotes: 22

Views: 28911

Answers (4)

DevonDahon
DevonDahon

Reputation: 8360

Using the spread operator seems a better choice to me to remove an array element without mutation:

let fruits = ['peach', 'pear', 'apple', 'plum'];
let result = [...fruits.slice(0, 2), ...fruits.slice(3)];

console.log(fruits); // ['peach', 'pear', 'apple', 'plum']
console.log(result); // ['peach', 'pear', 'plum']

Source

Upvotes: 1

ByteCoder
ByteCoder

Reputation: 1

var arr = [{id:1, name:'name'},{id:2, name:'name'},{id:3, name:'name'}];
var index = 1;
var result = Array.prototype.concat(arr.slice(0, index), arr.slice(index + 1, arr.length));

It merges left and right part of the array, the delimiter here is the element you want to delete.

Upvotes: 0

orpheus
orpheus

Reputation: 1140

You can use the es6 spread operator and Array.prototype.splice

var arr = [{id:1, name:'name'},{id:2, name:'name'},{id:3, name:'name'}];

let newArr = [...arr]
newArr.splice(index)

The spread operator copies the array and splice changes the contents of an array by removing or replacing existing elements and/or adding new elements

Upvotes: 4

c.P.u1
c.P.u1

Reputation: 17094

Array.prototype.filter will create and return a new array consisting of elements that match the predicate.

function removeByIndex(array, index) {
  return array.filter(function (el, i) {
    return index !== i;
  });
}

Even shorter with ECMAScript 6:

var removeByIndex = (array, index) => array.filter((_, i) => i !== index);

Upvotes: 34

Related Questions