假设我们有以下多维数组:
const myArray = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]];
我想集中讨论元素myArray[2][1]
,也就是7
。
如何在最快的算法中找到这个元素的单个索引,尽管有多维数组?
即,我如何找到在这个元素之前存在多少个不可分割的元素?
因此,在上面的示例中,先前不可分割的元素将是[0] = 1
、[1] = 2
、[2] = 3
、[3] = 4
、[4] = 5
、[5] = 6
,从而构成myArray[2][1]
、6
的总索引。
编辑:尽管本例显示最大的维度是三维,但是否可以使用一种算法来处理多达n个维度。
理想情况下是以下形式的函数:
Array.prototype.getOverallIndex(i, j, k, ...)
{
...
return overallIndex;
}
- 使用Array.prototype.flat(Infinity)来压平(任何深度)您的数组
- 使用Array.prototype.indexOf()获取所需项的索引
示例:
const myArray = [[[1, 2], 3], [4, 5], [6, 7], [7, 8], [9, 10]];
const flattened = myArray.flat(Infinity);
console.log(flattened.indexOf(7)) // 6
然后,如果你想要N的所有索引,你可以使用:
const indexesOf = (arr, num) => arr.flat(Infinity).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]
如果需要获得阵列的最大深度,您可以使用:
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]];
// levels deep:
const depth = getDepth(myArray);
console.log(depth); // 3
你可以数数。
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);