If we consider a 2D array:
┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│ 0 │ 2 │ 3 │ 2 │
│ 1 │ 3 │ 1 │ 3 │
│ 2 │ 2 │ 2 │ 3 │
└─────────┴───┴───┴───┘
The goal is to sort the elements in this 2D array and arrange them in a line from top to bottom as shown below:
┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 3 │
│ 1 │ 2 │ 2 │ 3 │
│ 2 │ 2 │ 3 │ 3 │
└─────────┴───┴───┴───┘
Currently, there is code available for this process:
const generateArray = (size, min, max) =>
Array(size)
.fill(0)
.map(() => generateNumber(min, max));
const generateArray2D = (rows, cols, min, max) =>
Array(rows)
.fill(0)
.map(() => generateArray(cols, min, max));
const generateNumber = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + Math.floor(min);
const generated2DArray = generateArray2D(
rows,
cols,
10,
30
);
const sortedArray = [...generated2DArray].flat(1).sort(((a, b) => a - b))
for (const sortedElement of sortedArray) {
for (let j = 0; j < generated2DArray.length; j++) {
for (let i = 0; i < generated2DArray[j].length; i++) {
generated2DArray[i][j] = sortedElement;
}
}
}
However, each field in the resulting array contains only the last element from the sorted sortedArray
like so:
┌─────────┬────┬────┬────┬────┬────┐
│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │
├─────────┼────┼────┼────┼────┼────┤
│ 0 │ 30 │ 30 │ 30 │ 30 │ 30 │
│ 1 │ 30 │ 30 │ 30 │ 30 │ 30 │
│ 2 │ 30 │ 30 │ 30 │ 30 │ 30 │
│ 3 │ 30 │ 30 │ 30 │ 30 │ 30 │
│ 4 │ 30 │ 30 │ 30 │ 30 │ 30 │
└─────────┴────┴────┴────┴────┴────┘
Several attempts were made to resolve this issue without success. Any suggestions on how to address this problem would be greatly appreciated.