简体   繁体   中英

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?

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))
const items = [0, 1, 2, 3, 4]; [1, 4, 3].reverse().forEach((index) => { items.splice(index, 1) }) // [0, 2, 4]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM