简体   繁体   中英

How do I loop through an array then filter it based on the output of .some()?

I am having difficulty trying to figure out how to use filter within a loop.

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

I believe there is an issue with line 5. When filter takes place, the element in [0] is removed, the second element that was at [1] now becomes [0] . Essentially, after the filter method is ran, filteredCityList[1][0] no longer exists for the loop to run as intended.

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);

Desired output:

filteredCityList = []

Current output:

filteredCityList = [["3", 2]]

Thank you for reading.

When you remove an element whose index is less than or equal to current loop's i , then you will possibly skip some elements in subsequent loops, one way around this problem is to use splice to remove elements and correct the i at the same time:

 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);

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