2 回答
TA贡献1815条经验 获得超13个赞
我认为这个问题令人困惑的部分是你基本上没有使用k. 你只检查对[ j, k[anything][0] ]
这k[anything][1]与过滤无关,对吗?如果是这样,请看下面的代码
const j = 1;
let k = [["0", 2],["3", 2],["5", 2]];
const roads = [[0,1],[0,3],[1,2],[1,3],[5,6],[5,7]];
// results will return the filtered array
// you can instead change `let results` to `k`
// if you want to set it directly
let results = k.filter(kPair => {
let roadsContainPair = roads.some(roadPair => {
// check the two cases
// [j, kPair[0]] and [kPair[0], j]
return (roadPair[0] === j && roadPair[1] === parseInt(kPair[0])) ||
(roadPair[0] === parseInt(kPair[0]) && roadPair[1] === j);
});
// since we only want the pair if roads DOESN'T contain it
// we return the negative of roadsContainPair
// i.e. if the current "pair" is found in roads, filter it out
return !roadsContainPair;
});
// results = [["5", 2]];
TA贡献1815条经验 获得超6个赞
用于some()测试数组中的条件是否匹配。在您的情况下使用它来if查看是否有任何对在roads.
用于includes()测试一个值是否在数组中。过滤时使用它k。
const j = 1;
let k = [
["0", 2],
["3", 2]
];
let roads = [
[0, 1],
[0, 3],
[1, 2],
[1, 3]
];
let k_parsed = k.map(([x]) => parseInt(x));
if (roads.some(([rx, ry]) => k_parsed.some(kx => (rx == j && ry == kx) || (rx == kx && ry == j)))) {
k = k.filter(([kx]) => !k_parsed.includes(parseInt(kx)));
}
console.log(k);
k = [["0", 2],["3", 2],["5", 2]];
roads = [[0,1],[0,3],[1,2],[1,3],[5,6],[5,7]];
k_parsed = k.map(([x]) => parseInt(x));
if (roads.some(([rx, ry]) => k_parsed.some(kx => (rx == j && ry == kx) || (rx == kx && ry == j)))) {
k = k.filter(([kx]) => !k_parsed.includes(parseInt(kx)));
}
console.log(k);
添加回答
举报