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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With