在JS中按值从数组中删除多个元素

时间:2015-11-08 16:58:04

标签: javascript arrays splice

当我想删除一个元素时,很容易。这是我的功能:

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

但是如何删除多个元素?

3 个答案:

答案 0 :(得分:5)

这是一个使用ES7的简单版本:

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

对于ES6的简单版本

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

答案 1 :(得分:0)

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

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

// [0, 2, 4]

答案 2 :(得分:-2)

我相信您会在Javascript的内置数组函数中找到您正在寻找的功能......特别是Array.map();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.