首页 > 解决方案 > 过滤数组,同时从已删除的相同索引中的其他数组中删除项目

问题描述

我正在寻找过滤一个数组(testCopy),该数组需要从被过滤掉的索引中删除来自其他并行数组(testCopy2 和 testCopy3)的项目。所以我希望得到类似 testCopy [0, 2]、testCopy2 [1,3] 和 testCopy3 [3,5] 的东西。因此,被删除的索引中的相同项目将从其他两个中删除。我尝试通过从过滤器传递索引来将它们切掉,但这似乎没有奏效,知道我该怎么做吗?

let test = [0, 1, 2, 4, 5];
let test2 = [1, 2, 3, 6, 5];
let test3 = [3, 4, 5, 8, 9];

let testCopy = [...test];
let testCopy2 = [...test2];
let testCopy3 = [...test3];

let testClone = testCopy.filter((item, index) => {
  if (item === 0 || item === 2) {
    return true;
  } else {
    testCopy2.splice(index, 1);
    testCopy3.splice(index, 1);
    return false
  }
});

console.log(testClone, testCopy2, testCopy3); // [0, 2],  [1, 3, 6], [3, 5, 8]

标签: javascriptarrays

解决方案


如果你不需要开始testCopy2testCopy3填充,你可以这样做:

let test = [0, 1, 2, 4, 5];
let test2 = [1, 2, 3, 6, 5];
let test3 = [3, 4, 5, 8, 9];

let testCopy = [...test];
let testCopy2 = [];
let testCopy3 = [];

let testClone = testCopy.filter((item, index) => {
  if (item === 0 || item === 2) {
    testCopy2.push(test2[index]);
    testCopy3.push(test3[index]);
    return true;
  } else {
    return false;
  }
});

console.log(testClone, testCopy2, testCopy3);


推荐阅读