Reputation: 11224
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
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']
Upvotes: 1
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
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
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