Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 911
Bazinga Avatar asked Dec 10 '14 08:12

Bazinga


People also ask

How can we copy array without mutating JavaScript?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from an array without splicing?

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.


1 Answers

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);
like image 181
c.P.u1 Avatar answered Sep 29 '22 20:09

c.P.u1