Remove multiple elements from array in Javascript/jQuery

JavascriptJquery

Javascript Problem Overview


I have two arrays. The first array contains some values while the second array contains indices of the values which should be removed from the first array. For example:

var valuesArr = new Array("v1","v2","v3","v4","v5");   
var removeValFromIndex = new Array(0,2,4);

I want to remove the values present at indices 0,2,4 from valuesArr. I thought the native splice method might help so I came up with:

$.each(removeValFromIndex,function(index,value){
    valuesArr.splice(value,1);
});
    

But it didn't work because after each splice, the indices of the values in valuesArr were different. I could solve this problem by using a temporary array and copying all values to the second array, but I was wondering if there are any native methods to which we can pass multiple indices at which to remove values from an array.

I would prefer a jQuery solution. (Not sure if I can use grep here)

Javascript Solutions


Solution 1 - Javascript

There's always the plain old for loop:

var valuesArr = ["v1","v2","v3","v4","v5"],
    removeValFromIndex = [0,2,4];    

for (var i = removeValFromIndex.length -1; i >= 0; i--)
   valuesArr.splice(removeValFromIndex[i],1);

Go through removeValFromIndex in reverse order and you can .splice() without messing up the indexes of the yet-to-be-removed items.

Note in the above I've used the array-literal syntax with square brackets to declare the two arrays. This is the recommended syntax because new Array() use is potentially confusing given that it responds differently depending on how many parameters you pass in.

EDIT: Just saw your comment on another answer about the array of indexes not necessarily being in any particular order. If that's the case just sort it into descending order before you start:

removeValFromIndex.sort(function(a,b){ return b - a; });

And follow that with whatever looping / $.each() / etc. method you like.

Solution 2 - Javascript

I suggest you use Array.prototype.filter

var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];
valuesArr = valuesArr.filter(function(value, index) {
     return removeValFrom.indexOf(index) == -1;
})

Solution 3 - Javascript

Here is one that I use when not going with lodash/underscore:

while(IndexesToBeRemoved.length) {
    elements.splice(IndexesToBeRemoved.pop(), 1);
}

Solution 4 - Javascript

Not in-place but can be done using grep and inArray functions of jQuery.

var arr = $.grep(valuesArr, function(n, i) {
    return $.inArray(i, removeValFromIndex) ==-1;
});

alert(arr);//arr contains V2, V4

check this fiddle.

Solution 5 - Javascript

A simple and efficient (linear complexity) solution using filter and Set:

const valuesArr = ['v1', 'v2', 'v3', 'v4', 'v5'];   
const removeValFromIndex = [0, 2, 4];

const indexSet = new Set(removeValFromIndex);

const arrayWithValuesRemoved = valuesArr.filter((value, i) => !indexSet.has(i));

console.log(arrayWithValuesRemoved);

The great advantage of that implementation is that the Set lookup operation (has function) takes a constant time, being faster than nevace's answer, for example.

Solution 6 - Javascript

This works well for me and work when deleting from an array of objects too:

var array = [ 
    { id: 1, name: 'bob', faveColor: 'blue' }, 
    { id: 2, name: 'jane', faveColor: 'red' }, 
    { id: 3, name: 'sam', faveColor: 'blue' }
];

// remove people that like blue

array.filter(x => x.faveColor === 'blue').forEach(x => array.splice(array.indexOf(x), 1));

There might be a shorter more effecient way to write this but this does work.

Solution 7 - Javascript

It feels necessary to post an answer with O(n) time :). The problem with the splice solution is that due to the underlying implementation of array being literally an array, each splice call will take O(n) time. This is most pronounced when we setup an example to exploit this behavior:

var n = 100
var xs = []
for(var i=0; i<n;i++)
  xs.push(i)
var is = []
for(var i=n/2-1; i>=0;i--)
  is.push(i)

This removes elements starting from the middle to the start, hence each remove forces the js engine to copy n/2 elements, we have (n/2)^2 copy operations in total which is quadratic.

The splice solution (assuming is is already sorted in decreasing order to get rid of overheads) goes like this:

for(var i=0; i<is.length; i++)
  xs.splice(is[i], 1)

However, it is not hard to implement a linear time solution, by re-constructing the array from scratch, using a mask to see if we copy elements or not (sort will push this to O(n)log(n)). The following is such an implementation (not that mask is boolean inverted for speed):

var mask = new Array(xs.length)
for(var i=is.length - 1; i>=0; i--)
  mask[is[i]] = true
var offset = 0
for(var i=0; i<xs.length; i++){
  if(mask[i] === undefined){
    xs[offset] = xs[i]
    offset++
  }
}
xs.length = offset

I ran this on jsperf.com and for even n=100 the splice method is a full 90% slower. For larger n this difference will be much greater.

Solution 8 - Javascript

function filtermethod(element, index, array) {  
    return removeValFromIndex.find(index)
}  
var result = valuesArr.filter(filtermethod);

MDN reference is here

Solution 9 - Javascript

In pure JS you can loop through the array backwards, so splice() will not mess up indices of the elements next in the loop:

for (var i = arr.length - 1; i >= 0; i--) {
    if ( yuck(arr[i]) ) {
        arr.splice(i, 1);
    }
}

Solution 10 - Javascript

A simple solution using ES5. This seems more appropriate for most applications nowadays, since many do no longer want to rely on jQuery etc.

When the indexes to be removed are sorted in ascending order:

var valuesArr = ["v1", "v2", "v3", "v4", "v5"];   
var removeValFromIndex = [0, 2, 4]; // ascending

removeValFromIndex.reverse().forEach(function(index) {
  valuesArr.splice(index, 1);
});

When the indexes to be removed are not sorted:

var valuesArr = ["v1", "v2", "v3", "v4", "v5"];   
var removeValFromIndex = [2, 4, 0];  // unsorted

removeValFromIndex.sort(function(a, b) { return b - a; }).forEach(function(index) {
  valuesArr.splice(index, 1);
});

Solution 11 - Javascript

Quick ES6 one liner:

const valuesArr = new Array("v1","v2","v3","v4","v5");   
const removeValFromIndex = new Array(0,2,4);

const arrayWithValuesRemoved = valuesArr.filter((value, i) => removeValFromIndex.includes(i))

Solution 12 - Javascript

If you are using underscore.js, you can use _.filter() to solve your problem.

var valuesArr = new Array("v1","v2","v3","v4","v5");
var removeValFromIndex = new Array(0,2,4);
var filteredArr = _.filter(valuesArr, function(item, index){
                  return !_.contains(removeValFromIndex, index);
                });

Additionally, if you are trying to remove items using a list of items instead of indexes, you can simply use _.without(), like so:

var valuesArr = new Array("v1","v2","v3","v4","v5");
var filteredArr = _.without(valuesArr, "V1", "V3");

Now filteredArr should be ["V2", "V4", "V5"]

Solution 13 - Javascript

You can correct your code by replacing removeValFromIndex with removeValFromIndex.reverse(). If that array is not guaranteed to use ascending order, you can instead use removeValFromIndex.sort(function(a, b) { return b - a }).

Solution 14 - Javascript

Here's one possibility:

valuesArr = removeValFromIndex.reduceRight(function (arr, it) {
    arr.splice(it, 1);
    return arr;
}, valuesArr.sort(function (a, b) { return b - a }));

Example on jsFiddle

MDN on Array.prototype.reduceRight

Solution 15 - Javascript

filter + indexOf (IE9+):

function removeMany(array, indexes) {
  return array.filter(function(_, idx) {
    return indexes.indexOf(idx) === -1;
  });
}); 

Or with ES6 filter + find (Edge+):

function removeMany(array, indexes = []) {
  return array.filter((_, idx) => indexes.indexOf(idx) === -1)
}

Solution 16 - Javascript

Here's a quickie.

function removeFromArray(arr, toRemove){
    return arr.filter(item => toRemove.indexOf(item) === -1)
}

const arr1 = [1, 2, 3, 4, 5, 6, 7]
const arr2 = removeFromArray(arr1, [2, 4, 6]) // [1,3,5,7]

Solution 17 - Javascript

Sounds like Apply could be what you are looking for.
maybe something like this would work?

Array.prototype.splice.apply(valuesArray, removeValFromIndexes );

Solution 18 - Javascript

var valuesArr = new Array("v1","v2","v3","v4","v5");   
var removeValFromIndex = new Array(0,2,4);

console.log(valuesArr)
let arr2 = [];

for (let i = 0; i < valuesArr.length; i++){
  if (    //could also just imput this below instead of index value
    valuesArr[i] !== valuesArr[0] && // "v1" <--
    valuesArr[i] !== valuesArr[2] && // "v3" <--
    valuesArr[i] !== valuesArr[4]    // "v5" <--
  ){
    arr2.push(valuesArr[i]);
  }
}

console.log(arr2);

This works. However, you would make a new array in the process. Not sure if thats would you want or not, but technically it would be an array containing only the values you wanted.

Solution 19 - Javascript

You can try Lodash js library functions (_.forEach(), _.remove()). I was using this technique to remove multiple rows from the table.

let valuesArr = [
    {id: 1, name: "dog"}, 
    {id: 2, name: "cat"}, 
    {id: 3, name: "rat"}, 
    {id: 4, name: "bat"},
    {id: 5, name: "pig"},
]; 
let removeValFromIndex = [
    {id: 2, name: "cat"}, 
    {id: 5, name: "pig"},
]; 
_.forEach(removeValFromIndex, (indi) => {
    _.remove(valuesArr, (item) => {
        return item.id === indi.id;
    });
})
console.log(valuesArr)
/*[
    {id: 1, name: "dog"},  
    {id: 3, name: "rat"}, 
    {id: 4, name: "bat"},
];*/ 

Don't forget to clone (_.clone(valuesArr) or [...valuesArr]) before mutate your array

Solution 20 - Javascript

Try this

var valuesArr = new Array("v1", "v2", "v3", "v4", "v5");
console.info("Before valuesArr = " + valuesArr);
var removeValFromIndex = new Array(0, 2, 4);
valuesArr = valuesArr.filter((val, index) => {
  return !removeValFromIndex.includes(index);
})
console.info("After valuesArr = " + valuesArr);

Solution 21 - Javascript

I find this the most elegant solution:

const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]

const newArray = oldArray.filter((value) => {
    return !removeItems.includes(value)
})

console.log(newArray)

output:

[2, 4]

Solution 22 - Javascript

You could try and use delete array[index] This won't completely remove the element but rather sets the value to undefined.

Solution 23 - Javascript

removeValFromIndex.forEach(function(toRemoveIndex){
    valuesArr.splice(toRemoveIndex,1);
});

Solution 24 - Javascript

For Multiple items or unique item:

I suggest you use Array.prototype.filter

Don't ever use indexOf if you already know the index!:

var valuesArr = ["v1","v2","v3","v4","v5"];
var removeValFrom = [0, 2, 4];

valuesArr = valuesArr.filter(function(value, index) {
     return removeValFrom.indexOf(index) == -1;
}); // BIG O(N*m) where N is length of valuesArr and m is length removeValFrom

#Do: with Hashes... using Array.prototype.map

  var valuesArr = ["v1","v2","v3","v4","v5"];
  var removeValFrom = {};
  ([0, 2, 4]).map(x=>removeValFrom[x]=1); //bild the hash.
  valuesArr = valuesArr.filter(function(value, index) {
      return removeValFrom[index] == 1;
  }); // BIG O(N) where N is valuesArr;

Solution 25 - Javascript

You could construct a Set from the array and then create an array from the set.

const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjinkyaView Question on Stackoverflow
Solution 1 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 2 - JavascriptSasha DavydenkoView Answer on Stackoverflow
Solution 3 - JavascriptDan OchianaView Answer on Stackoverflow
Solution 4 - JavascriptTheVillageIdiotView Answer on Stackoverflow
Solution 5 - JavascriptAlberto Trindade TavaresView Answer on Stackoverflow
Solution 6 - JavascriptStuartMcView Answer on Stackoverflow
Solution 7 - JavascriptsimonzackView Answer on Stackoverflow
Solution 8 - Javascripthrishikeshp19View Answer on Stackoverflow
Solution 9 - JavascriptWatchduckView Answer on Stackoverflow
Solution 10 - JavascriptKaspar FennerView Answer on Stackoverflow
Solution 11 - JavascriptnevaceView Answer on Stackoverflow
Solution 12 - JavascriptJohnny ZhaoView Answer on Stackoverflow
Solution 13 - JavascriptminopretView Answer on Stackoverflow
Solution 14 - JavascriptOlli KView Answer on Stackoverflow
Solution 15 - JavascriptdaviestarView Answer on Stackoverflow
Solution 16 - JavascriptMerrick KavolskyView Answer on Stackoverflow
Solution 17 - JavascriptRobView Answer on Stackoverflow
Solution 18 - Javascriptuser2785628View Answer on Stackoverflow
Solution 19 - JavascriptEgilsView Answer on Stackoverflow
Solution 20 - Javascriptpathe.kiranView Answer on Stackoverflow
Solution 21 - JavascriptArtur Müller RomanovView Answer on Stackoverflow
Solution 22 - JavascriptHenesnarfelView Answer on Stackoverflow
Solution 23 - JavascriptRamesh VishnoiView Answer on Stackoverflow
Solution 24 - JavascriptAlvaro JoaoView Answer on Stackoverflow
Solution 25 - JavascriptMohibView Answer on Stackoverflow