假设我有 4 个数组:
var arrays = [
[1, 2, 1],
[1, 3, 4],
[1, 2, 3],
[0, 2, 2]
];
我想返回以 1 和 2 开头的子数组,我需要什么类型的循环?
目前,这就是我所拥有的:
var arrays = [
[1, 2, 1],
[1, 3, 4],
[1, 2, 3],
[0, 2, 2]
];
var selected = [1, 2]; // These are the values that need to match
var result = [];
for (var i = 0; i < selected.length; i++) {
for (var j = 0; j < arrays.length; j++) {
if (arrays[i][j] === selected[i]) {
result.push(arrays[i]);
}
}
}
当 selected
数组中有超过 1 个值时,它似乎会返回所有与第二个索引上的 2 匹配的值,因此结果将是:
[
[1, 2, 1],
[1, 2, 3],
[0, 2, 2]
]
循环需要确保在第二次迭代时确保第一个值仍然为真,正如我的预期结果:
[
[1, 2, 1],
[1, 2, 3]
]
请有人帮助我,我已经尝试了数百个不同的循环并检查了 2-3 天的变化。
非常感谢!!
jack
最佳答案
每当 arrays
和 selected
之间的任何给定索引匹配时,当前代码都会推送到结果数组。相反,您需要反转循环并为每个子数组迭代 selected
并检查每个元素是否匹配,如果不匹配则打破
内部循环并且不推送。
const arrays = [
[1, 2, 1],
[1, 3, 4],
[1, 2, 3],
[0, 2, 2],
];
const selected = [1, 2]; // These are the values that need to match
const result = [];
for (let i = 0; i < arrays.length; i++) {
let match = true;
for (let j = 0; j < selected.length; j++) {
if (arrays[i][j] !== selected[j]) {
match = false;
break;
}
}
if (match) {
result.push(arrays[i]);
}
}
console.log(result);
更现代的解决方案是使用 filter()
带有嵌套 every()
调用选定的
。
const arrays = [
[1, 2, 1],
[1, 3, 4],
[1, 2, 3],
[0, 2, 2],
];
var selected = [1, 2];
const result = arrays.filter(arr => selected.every((n, i) => n === arr[i]));
console.log(result);
关于javascript - 循环数组并返回与前 2 个值匹配的子数组的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74724175/