I need to generate a multidimensional array from a multidimensional array.
For example, my array:
var codes = [
['2', '12521', '3'],
['3', '32344', '2'],
['3', '35213', '2'],
['4', '42312', '2'],
['4', '41122', '1'],
['5', '51111', '1']
];
And I need to group the array based on element: For example grouping based on 1st element:
[0] => Array
(
[0] => Array
(
[0] => '2'
[1] => '12521'
}
)
[1] => Array
(
[0] => Array
(
[0] => '3'
[1] => '32344'
[2] => '3'
}
[1] => Array
(
[0] => '3'
[1] => '35213'
[2] => '2'
}
)
[2] => Array
(
[0] => Array
(
[0] => '4'
[1] => '42312'
[2] => '2'
}
[1] => Array
(
[0] => '4'
[1] => '41122'
[2] => '1'
}
)
...
var codes = [
['2', '12521', '3'],
['3', '32344', '2'],
['3', '35213', '2'],
['4', '42312', '2'],
['4', '41122', '1'],
['5', '51111', '1']
];
const output = codes.reduce(({result, current}, [x, ...y]) => {
if (current !== x) result.push([]);
result[result.length - 1].push([x, ...y]);
return {result, current: x};
}, {result: []}).result;
console.log(output);
For the function , i can group based on the 1st element. But what if I need to group based on 2nd , 3rd element, any ways to do it without switching the position of the array elements (for example, not switching 3rd element to the 1st position and run the function)