Search code examples
javascriptarraysobjectreduce

Best way of returning indexes on a multi-dimensional array object with Javascript


I'am trying to create a season long score sheet for Formula One races. Each Season is an array that has an object for each race that in turn holds the participants drivers car number and their grid number.

If I want to be able to find the grid numbers for all the drivers that took part in race four, thus I want to go through the driver object and find any driver that matches the criteria and return both the index of the driver and the the index number of the grid array and pass it back as an array.

In this case an array would be returned as:

[3,1],[6,2]

Thus, f1[0][0].race[0].driver[3][1] = 4 && f1[0][0].race[0].driver[6][2] = 4;

I have looked at the reduce method, which works but can't figure it out when using a two dimension array like f1[0][0].

I know for this example I could just use a for loop but potentially over time this array will get a lot bigger.

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


Solution

  • Your provided data is kinda misleading. Anyways you can find the sample multi-dimensional array index finding functionality usage below:

    // Imagine you have a multidimensional array of 3x3 like below :
    
    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; // Searching value
    
    console.log(JSON.stringify(findIndexes(multiDimensionalArray, targetValue))); // Value 2 is in 0th row 1st column (Array indexes start with zero base)