185

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)

27 Answers 27

346

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.

Sign up to request clarification or add additional context in comments.

12 Comments

wont slicing mess up the index
@MuhammadUmer - No, not if you do it correctly, which is what my answer explains.
+1, I didn't realized I had to do the splice in reverse order, although instead of using forEach, my approach is using $.each(rvm.reverse(), function(e, i ) {})
this will only work if removeValFromIndex is in sorted in ascending order
@KunalBurangi - the answer explicitly covers sorting.
|
59

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

3 Comments

indexOf inside of filter... not optimum
upvote. faster than the splice method according to jsperf.com/remove-multiple/1
Yes it's faster than splice but will create a new array, not delete items in place.
37

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

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

6 Comments

Elegant solution! At first I thought this wouldn't work because I thought that every time you call slice you would have to recalculate the indexes to be removed (-1 on IndexestoBeRemoved), but it actually works!
Too much clever
This solution is worked if only IndexesToBeRemoved array is sorted by ascending.
Those indices will be invalidated after the first splice.
@shinzou - Not if IndexesToBeRemoved is sorted (ascending).
|
19

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.

1 Comment

yes has was not working with arrays earlier I tried [...new Set(xyz)]
18

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.

4 Comments

It would be (close enough to) in-place if you just said valuesArr = $.grep(...);
@nnnnnn ha ha ha I was leaving for a meeting (you know they make you so productive) so did not experiment much.
@cept0 Why the downvote? OP asked for a jQuery solution.
jsfiddler - Error 404. We're truly sorry, but there is no such page.
13

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

Comments

11

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.

Comments

10

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.

Comments

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

MDN reference is here

3 Comments

@riship89 The fiddle is down
@Karna: fiddle is down
Please note that at the time of writing (june 2014), Array.prototype.find is part of the current ES6 draft and only implemented in current firefox
6

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

1 Comment

Does not work yuck is not a function, so assumed it is the index of unwanted element indexes, & used yuck[arr[i]]
5

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

Comments

5

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

1 Comment

Your code should run faster if you make removeValFromIndex a Set() and use removeValFromIndex.has instead of includes.
2

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

1 Comment

How contains is implemented in underscore... be careful if it's equivalent to indexOf inside of filter... not optimum at all...
1

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

2 Comments

Looks good to me - jsfiddle.net/mrtsherman/gDcFu/2. Although this makes the supposition that the removal list is in order.
@minopret: Thanks but it will only work if indexes in removeValFromIndex are in ascending order.
1

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

Comments

1

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

1 Comment

indexOf inside of filter... not optimum
1

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]

1 Comment

indexOf inside of filter... not optimum
1

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

Comments

0

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

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

1 Comment

But the .splice() method is not expecting a list of elements to remove, it is expecting a single index of the element at which to start removing followed by the number of elements to remove...
0
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.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

-1

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

1 Comment

Thanks but I want to remove the elements.
-1
removeValFromIndex.forEach(function(toRemoveIndex){
    valuesArr.splice(toRemoveIndex,1);
});

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
-2

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;

Comments

-2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.