javascript 将索引数据从一个数组提取到另一个数组[重复]

6l7fqoea  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(123)
    • 此问题在此处已有答案**:

(9个答案)
21小时前关门了。
假设我们有一个一维数组data,存储从0到n的整数。我试图将这个数组处理成一个多维数组result,这样result[n][x]存储n在data中第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"]
]

我想知道我想要的是否可能,如果可能,如何实现。

xkrw2x1b

xkrw2x1b1#

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)
bzzcjhmw

bzzcjhmw2#

查看此处:查找元素的所有匹配项
示例中的一维indices数组将对应于多维result数组,因此在循环中,您将执行result[n].push(idx)

w6mmgewl

w6mmgewl3#

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

相关问题