I am currently working on a project where I store numeric values in a JS array. After some changes it should be removed again. I currently use the array.splice method like this:
function removeA(arr, element) {
var index = arr.indexOf(element);
if (index >= 0) {
arr.splice(index, 1 );
}
return arr;
}
But this seems to give me issues on Safari. This piece of code works in every browser, like Chrome, Firefox, Opera. But not on Safari. It even works in the Technical Preview of Safari.
Does anyone have an alternative?
Thanks in advance :)
You have to slice before and after the index, and concat
the results. Note that Array.prototype.slice()
doesn't mutate the original array like Array.prototype.splice()
does.
var arr = [0, 1, 2, 3, 4, 5, 6, 7];
var index = 5;
var result = arr.slice(0, index).concat(arr.slice(index + 1));
console.log(result);
Or using ES6 and array spread:
var arr = [0, 1, 2, 3, 4, 5, 6, 7];
var index = 5;
var result = [...arr.slice(0, index), ...arr.slice(index + 1)];
console.log(result);
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