如何遍历数组,然后根据.some()的输出对其进行过滤?

时间:2020-10-21 00:43:04

标签: javascript arrays for-loop filter

我很难弄清楚如何在循环中使用过滤器。

const roads = [[0,1],[0,3],[1,2],[1,3]];
const cityWithMostRoads = 1;
let filteredCityList = [["0", 2],["3", 2]];

我认为第5行存在问题。发生filter时,[0]中的元素将被删除,位于[1]的第二个元素现在变为{{1} }。本质上,运行[0]方法后,filter不再存在,循环无法按预期运行。

filteredCityList[1][0]

所需的输出:

1   if(filteredCityList.length > 0) {      
2      for(let i = 0; i < filteredCityList.length; i++) {
3      let pair = ([a, b]) => a == filteredCityList[i][0] && b == cityWithMostRoads || a == cityWithMostRoads && b == filteredCityList[i][0];
4        if(roads.some(pair)) {
5          filteredCityList = filteredCityList.filter(x => x[0] !== filteredCityList[i][0])
6        };
7      };
8   };
9 
10  console.log(filteredCityList);

当前输出:

filteredCityList = []

感谢您阅读。

1 个答案:

答案 0 :(得分:1)

当删除索引小于或等于当前循环的i的元素时,可能会在后续循环中跳过某些元素,解决此问题的一种方法是使用splice删除元素并同时更正i

const roads = [[0,1],[0,3],[1,2],[1,3]];
const cityWithMostRoads = 1;
let filteredCityList = [["0", 2],["3", 2]];

 if(filteredCityList.length > 0) {      
     for(let i = 0; i < filteredCityList.length; i++) {

     let pair = ([a, b]) => a == filteredCityList[i][0] && b == cityWithMostRoads || a == cityWithMostRoads && b == filteredCityList[i][0];
       if(roads.some(pair)) {
         let target = filteredCityList[i][0];
         //loops backwards to remove elements 
         for(let j = filteredCityList.length - 1; j >= 0; j--){
            if(filteredCityList[j][0] === target){
               filteredCityList.splice(j, 1);
               if(j <= i) i--; // correct `i`
            }
         }
 
       };
     };
  };
 
console.log(filteredCityList);