10

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]

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah yeah! The filter... Duh! I wish es6 had implemented non-fat arrow notation, or at least provided a fn keyword. Writing function everywhere makes one-liner so hard to fit in 80 characters.
@user1534422 with one arrow, You could do it this way: const arrayWithoutElementAtIndex = (arr, index, newArr = [...arr]) => (newArr.splice(index,1), newArr), you can see my answer edition. Excuse my english
code golf: const filter = (arr, index) => arr.filter((_, i) => index !== i);
0

You can do it in 2 operation using splice(), but won't be looking that nice

'use strict'

const arrayWithoutElementAtIndex = function(arr, index) {
  var ret = arr.slice(); //make a copy
  ret.splice(index, 1); //remove the item from given index
  return ret; //return the copy
}

var array = [1, 2, 4, 8, 16, 32, 64];
var array2 = arrayWithoutElementAtIndex(array, 3) // [1, 2, 4, 16, 32, 64]

snippet.log(array)
snippet.log(array2)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

1 Comment

Yeah, I was trying to avoid splice because you always end up with three times more lines ;)
0

With lodash:

_(this.state.additionalOwners, index).splice(index, 1).value())

Comments

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.