Ajinkya
Ajinkya

Reputation: 22730

Remove multiple elements from array in Javascript/jQuery

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)

Upvotes: 185

Views: 304044

Answers (27)

Jackson Quintero
Jackson Quintero

Reputation: 188

An alternative is to create a reducer, validate it by the index that returns the non-selected values and then order it.

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

  const data = valuesArr
    .reduce((p, c, i) => (!r.includes(i) ? [...p, c] : p), [])
    .sort((a, b) => b - a);

  console.log(data);

Upvotes: 0

Randhir Rawatlal
Randhir Rawatlal

Reputation: 363

This is more of a tweak to the answer by @nnnnnn, but I would also remove potential duplicate indices as this will otherwise cause additional rows to be deleted:

function arrayUnique(arr) {
    return arr.filter((value, index, array) => array.indexOf(value) === index);
}

function arrayDeleteMulti(arr, idxSet) {

    idxSet = arrayUnique(idxSet).sort(function(a,b){ return a-b; });
    
    for (var i = idxSet.length -1; i >= 0; i--)
        arr.splice(idxSet[i],1);

    return arr
}

So in this test

var arr = [`v0`, `v1`, `v2`, `v3`, `v4`, `v5`];
console.log(arrayDeleteMulti(arr, [4,4,4,0,2]))

We do get

[ "v1", "v3", "v5" ]

Upvotes: 0

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]

or even shorter:

const newArray = oldArray.filter(v => !removeItems.includes(v))

Upvotes: 13

pathe.kiran
pathe.kiran

Reputation: 2482

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

Upvotes: 1

Egils
Egils

Reputation: 1

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

Upvotes: 0

Ramesh Vishnoi
Ramesh Vishnoi

Reputation: 1396

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

Upvotes: -1

Mohib
Mohib

Reputation: 1

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]

Upvotes: -2

StuartMc
StuartMc

Reputation: 676

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.

Upvotes: 11

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

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.

Upvotes: 19

user2785628
user2785628

Reputation:

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.

Upvotes: 0

nevace
nevace

Reputation: 817

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

Upvotes: 5

Alvaro Silvino
Alvaro Silvino

Reputation: 9763

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;

Upvotes: -2

Merrick Kavolsky
Merrick Kavolsky

Reputation: 11

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]

Upvotes: 1

daviestar
daviestar

Reputation: 4641

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

Upvotes: 1

Sasha Davydenko
Sasha Davydenko

Reputation: 904

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;
})

Upvotes: 59

Kaspar Fenner
Kaspar Fenner

Reputation: 161

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);
});

Upvotes: 5

Dan Ochiana
Dan Ochiana

Reputation: 3408

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

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

Upvotes: 37

simonzack
simonzack

Reputation: 20968

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.

Upvotes: 10

Watchduck
Watchduck

Reputation: 1156

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);
    }
}

Upvotes: 6

Johnny Zhao
Johnny Zhao

Reputation: 2898

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"]

Upvotes: 2

Olli K
Olli K

Reputation: 1760

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

Upvotes: 1

hrishikeshp19
hrishikeshp19

Reputation: 9036

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

MDN reference is here

Upvotes: 7

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 346

minopret
minopret

Reputation: 4806

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 }).

Upvotes: 1

TheVillageIdiot
TheVillageIdiot

Reputation: 40512

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.

Upvotes: 18

Rob
Rob

Reputation: 3066

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

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

Upvotes: 0

Henesnarfel
Henesnarfel

Reputation: 2139

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

Upvotes: -1

Related Questions