0

Let's say we have a single dimension array data storing integers that are ranged from 0 to n. I was trying to process this array into a multidimensional array result such that result[n][x] stores the index of the x+1 th appearance of n in data.

For example, given the following 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
];

I wanted result to be like this.

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

However, the method I have used did not produce the result I was looking for. My method and the results are

// 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"]
]

I would like to know if what I wanted is even possible and if possible, how.

  • also [Array.fill(Array) creates copies by references not by value](https://stackoverflow.com/questions/37949813/array-fillarray-creates-copies-by-references-not-by-value) – pilchard Dec 31 '22 at 00:15
  • [don't use `for...in` on arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in) prefer a `for` loop or `for...of` over the `array.entries()`. And rather than creating a sparse array, use an object keyed by each element. – pilchard Dec 31 '22 at 00:20

3 Answers3

-1

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)
Konrad
  • 21,590
  • 4
  • 28
  • 64
-1

Look here: Finding all the occurrences of an element

The one-dimenstional indices array in the example would correspond to your multidimensional result array, so in your loop, you would do result[n].push(idx)

doctorjay
  • 91
  • 6
-1
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;
}