假设我们有一个单维数组data
,存储范围从0到n的整数。我试图将该数组处理成一个多维数组result
,使result[n][x]
存储data
中n的x+1次出现的索引。
例如,给定以下data
,
var data = [
2, 3, 4, 2, 5,
6, 8, 3, 6, 5,
1, 3, 5, 6, 1,
0, 6, 4, 2, 3,
4, 5, 6, 7, 1
];
我希望result
是这样的。
result
[
0: [15],
1: [10, 14, 24],
2: [ 0, 3, 18],
3: [ 1, 7, 11, 19],
4: [ 2, 17, 20],
5: [ 4, 9, 12, 21],
6: [ 5, 8, 13, 16, 22],
7: [23],
8: [6]
]
然而,我所使用的方法并没有产生我想要的结果。我的方法和结果是
// method
var result= new Array(9).fill([]);
for (var i in data) {
result[data[i]].push(i);
}
// result
result
[
0: ["0", "1", "2", "3", "4", "5", "6", "7", ... , "20", "21", "22", "23", "24"],
1: ["0", "1", "2", "3", "4", "5", "6", "7", ... , "20", "21", "22", "23", "24"],
2: ["0", "1", "2", "3", "4", "5", "6", "7", ... , "20", "21", "22", "23", "24"],
...
7: ["0", "1", "2", "3", "4", "5", "6", "7", ... , "20", "21", "22", "23", "24"],
8: ["0", "1", "2", "3", "4", "5", "6", "7", ... , "20", "21", "22", "23", "24"]
]
我想知道我想要的是否可能,如果可能,如何实现。
const data = [
2, 3, 4, 2, 5,
6, 8, 3, 6, 5,
1, 3, 5, 6, 1,
0, 6, 4, 2, 3,
4, 5, 6, 7, 1
];
// use `fill([]) creates one array and uses it 9 times
// instead create new array for each item
const result = [...Array(9)].map(() => [])
for (const i in data) {
result[data[i]].push(+i);
}
console.log(result)
看这里:查找出现的所有元素
示例中的一维indices
数组将对应于多维result
数组,因此在循环中,您将执行result[n].push(idx)
const result = [];
const indices = {};
for (let i = 0; i < data.length; i++) {
const value = data[i];
if (!indices[value]) {
indices[value] = 0;
}
const index = indices[value];
if (!result[value]) {
result[value] = [];
}
result[value][index] = i;
indices[value] += 1;
}