22

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.

1
  • 8
    check the 'slice' method :) Commented Dec 10, 2014 at 8:52

4 Answers 4

34

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thats not changed the original?
@anguLaravel, no, it won't mutate the original array.
4

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

1 Comment

You should call out that .splice() returns the REMOVED elements, as opposed to the new array without the item at that index.
1

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

Comments

0
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.

1 Comment

You could also spread here, instead of using concat. var result = [...arr.slice(1)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.