Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array without element at index

I implemented a function to get a shallow copy of an array without a specific element (using its index).

But I have to call three methods to achieve this. Is there a better way of doing this?

const arrayWithoutElementAtIndex = function (arr, index) {
    return arr.slice(0, index).concat(arr.slice(index + 1))
}

arrayWithoutElementAtIndex([1, 2, 4, 8, 16, 32, 64], 3) // [1, 2, 4, 16, 32, 64]
like image 208
user1534422 Avatar asked Jul 03 '15 09:07

user1534422


1 Answers

How about a regular filter?

const arrayWithoutElementAtIndex = function (arr, index) {
  return arr.filter(function(value, arrIndex) {
    return index !== arrIndex;
  });
}
document.write(arrayWithoutElementAtIndex([1, 2, 4, 8, 16, 32, 64], 3)); // [1, 2, 4, 16, 32, 64]

This would mean you only have a single function and it returns a new array instance.

like image 111
CodingIntrigue Avatar answered Nov 02 '22 03:11

CodingIntrigue