Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to array.splice in JavaScript

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 :)

like image 225
nns Avatar asked Dec 03 '22 23:12

nns


1 Answers

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);
like image 160
Ori Drori Avatar answered Dec 21 '22 23:12

Ori Drori