Home > database >  Finding the single index of an element in a multidimensional array (number of elements that exist be
Finding the single index of an element in a multidimensional array (number of elements that exist be

Time:01-23

Assume we have the following multidimensional array:

const myArray = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]];

and I want to focus on element myArray[2][1], which is 7.

How can I find the single index of this element, despite the multidimensional array, in the fastest possible algorithm?

i.e. How can I find how many indivisible elements exist before this element?

So in the example above, the previous indivisible elements would be [0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 5, [5] = 6 making the overall index of myArray[2][1], 6 .

Edit: Even though this example shows the largest dimension being 3-dimensions, is it possible to have an algorithm working for up to n-dimensions.

Ideally a function of the following form:

Array.prototype.getOverallIndex(i, j, k, ...)
{
...
return overallIndex;
}

CodePudding user response:

As an example, you might want to:

Example:

const getDepth = (a) => Array.isArray(a) ? 1   Math.max(0, ...a.map(getDepth)) : 0;
    
const myArray = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]];
const flattened = myArray.flat(getDepth(myArray));
console.log(flattened.indexOf(7)) // 6

Then, if you want all the indexes of N, you could use:

const getDepth = (a) => Array.isArray(a) ? 1   Math.max(0, ...a.map(getDepth)) : 0;
const indexesOf = (arr, num) => arr.flat(getDepth(myArray)).reduce((a, n, i) => (num === n && a.push(i), a), []);

// Use like:
const myArray = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]];
console.log(indexesOf(myArray, 7)) // [6, 7]

CodePudding user response:

You could count.

const
    getCount = v => Array.isArray(v)
        ? v.reduce((t, w) => t   getCount(w), 0)
        : 1,
    getCountOfItemsBefore = (array, target) => {
        let i = 0,
            count = 0;

        while (i < target[0]) count  = getCount(array[i  ]);

        if (target.length > 1 && Array.isArray(array[target[0]])) {
            count  = getCountOfItemsBefore(array[target[0]], target.slice(1));
        }
        return count;
    },
    data = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]],
    target = [2, 1],
    result = getCountOfItemsBefore(data, target);

console.log(result);

  • Related