我正在尝试为一级方程式比赛创建一份整个赛季的得分表。每个赛季都是一个数组,其中每场比赛都有一个对象,该对象又包含参与者车手的车号和发车号。
如果我希望能够找到参加第四场比赛的所有车手的发车号码,那么我想遍历车手对象并找到符合条件的任何车手,并返回车手的索引和网格数组的索引号并将其作为数组传回。
在这种情况下,数组将返回为:
[3,1],[6,2]
因此,f1[0][0].race[0].driver[3][1] = 4 && f1[0][0].race[0].driver[6][2] = 4;
我看过reduce方法,它可以工作,但在使用像f1[0][0]这样的二维数组时无法弄清楚。
我知道在这个例子中我可以只使用 for 循环,但随着时间的推移,这个数组可能会变得更大。
f1 = [];
f1[0] = [];
f1[0][0] = {};
f1[0][0].race = [];
f1[0][0].race[0] = {};
for(n=0; n<=10; n++){
f1[0][0].race[0].driver[n] = [];
f1[0][0].race[0].grid[n] = [];
};
f1[0][0].race[0].driver[3] = [2,4,6,8,10];
f1[0][0].race[0].grid[3] = [4,9,3,2,7];
f1[0][0].race[0].driver[6] = [1,3,4,6];
f1[0][0].race[0].grid[6] = [3,7,2,1];
f1[0][0].race[0].driver[8] = [2,3,8];
f1[0][0].race[0].grid[8] = [5,4,1];
const multiDimensionalArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
function findIndexes(arr, targetValue, currentPath = []) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const indexes = findIndexes(arr[i], targetValue, [...currentPath, i]);
if (indexes.length > 0) {
return indexes;
}
} else if (arr[i] === targetValue) {
return [...currentPath, i];
}
}
return [];
}
let targetValue = 2;
console.log(JSON.stringify(findIndexes(multiDimensionalArray, targetValue)));