Array.slice使用另一个数组中包含的索引号

时间:2018-11-14 13:39:23

标签: javascript arrays

我有两个数组。我正在尝试从[arr]中的[removeIndex]中的索引号中删除一些元素。

var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length;i++){
arr.splice(removeIndex[i],1);
}
console.log(arr)

// output Array(5) [ 1, 1, 0, 1, 1 ]
//expected [ 1,1,1,1,1]

0都位于arr [2]和arr [3]位置,应该将其删除,但是上面的代码不起作用。我怀疑它与循环重新排列索引号有关。是否有替代解决方案?

4 个答案:

答案 0 :(得分:1)

您绝对正确地怀疑为什么会这样。我想到的最简单的方法是对传递给filter方法的回调函数使用不常用的第二个参数,该方法采用元素的索引:

arr = arr.filter((elt, index) => removeIndex.indexOf(index) == -1);

答案 1 :(得分:1)

您可以使用Array.prototype.filter()

  

filter()方法将创建一个新数组,其中包含所有通过提供的功能实现的测试的元素。

Array.prototype.includes()

  

includes()方法确定数组是否包含某个元素,并在适当时返回true或false。

传递 index 作为第二个参数,以检查 index 是否包含在removeIndex中。仅在removeIndex数组中不存在当前 index 时返回元素:

var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
arr = arr.filter((i,idx) => !removeIndex.includes(idx));
console.log(arr); //[ 1,1,1,1,1]

答案 2 :(得分:0)

如注释中所述,您对数组进行了更改,因此,下次在数组中循环访问时,它的项目将被更改,并且在相同的索引处不会有相同的项目。对于您的特定示例,有一个相当简单的解决方案:

var removeIndex = [2,3].sort(); // This won't work with [3,2] for example
var arr = [1,1,0,0,1,1,1];

for (let i = 0; i < removeIndex.length; i++){
  arr.splice(removeIndex[i] - i, 1);
}

console.log(arr)

但是我建议例如使用.filter的不可变解决方案,例如注释中的建议

答案 3 :(得分:0)

我将使用filter并给出以下干净代码:

var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
var newArr = arr.filter(el => el !== 0);
console.log(newArr);
// [1,1,1,1,1]