Valeriu
Valeriu

Reputation: 171

Remove multiple elements from array by value in JS

When I want to remove one element, it is easy. This is my function:

function removeValues(array, value) {
    for(var i=0; i<array.length; i++) {
        if(array[i] == value) {
            array.splice(i, 1);
            break;
        }
    }
    return array;
}

But how do I remove multiple elements?

Upvotes: 1

Views: 14072

Answers (3)

const items = [0, 1, 2, 3, 4];

[1, 4, 3].reverse().forEach((index) => {
    items.splice(index, 1)
})

// [0, 2, 4]

Upvotes: 0

JDCL32
JDCL32

Reputation: 276

Here a simple version using ES7:

// removing values
let items = [1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => !valuesToRemove.includes(i))

For a simple version for ES6

// removing values
let items =[1, 2, 3, 4];
let valuesToRemove = [1, 3, 4]
items = items.filter((i) => (valuesToRemove.indexOf(i) === -1))

Upvotes: 16

kurt
kurt

Reputation: 1156

I believe you will find the kind of functionality you are looking for in Javascript's built in array functions... particularily Array.map(); and Array.filter();

//Array Filter
function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]


//Array Map (Can also be used to filter)
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

/////UPDATE REFLECTING REMOVAL OF VALUES USING ARRAY MAP

var a = [1,2,3,4,5,6];
a.map(function(v,i){
  if(v%2==0){
	a.pop(i);
  }
});
console.log(a);

// as shown above all array functions can be used within the call back to filter the original array. Alternativelty another array could be populated within the function and then aassigned to the variable a effectivley reducing the array.

Upvotes: -2

Related Questions