I'm currently working on creating a list that contains all the distinct levels within a multidimensional array of objects.
Given this dataset...
let levels = [
["P", "B", "L"],
["A", "B", "L3"],
["A", "B", "L3"],
["P", "B", "M"],
["P", "C", "L"],
["A", "C", "L3"]
];
The desired output should be structured like this:
const result = [
[1, 'P', 11, 'P.B', 111, 'P.B.L'],
[1, 'P', 12, 'P.C', 121, 'P.C.L'],
[2, 'A', 21, 'A.B', 211, 'A.B.L3']
];
Please note:
Each entry in the array represents a unique level.
Level identifiers:
1 => Level 1
11 => Level 1 and its sub-level
111 => Level 1, its sub-level, and the next level down
For each new Level 1, the identifier increments as follows for subsequent levels and their sub-levels:
2 => New Level 1
21 => New Level 1 and its sub-level
211 => New Level 1, its sub-level, and the sub-level's level
I am encountering difficulties in determining the level identifiers for each distinct pair. At this point, I have only managed to return the unique pairs as shown here:
function updateLevels(levels) {
const { result } = levels.reduce(
(acc, crr) => {
const l1Key = crr[0];
const l2Key = `${l1Key}.${crr[1]}`;
const l3Key = `${l2Key}.${crr[2]}`;
if (!acc.checkMap[l3Key]) {
acc.checkMap[l3Key] = true;
acc.result.push([l1Key, l2Key, l3Key]);
}
return acc;
},
{
checkMap: {},
result: [],
}
);
return result;
}
const result =
[
['P', 'P.B', 'P.B.L'],
['A', 'A.B', 'A.B.L3'],
['P', 'P.B', 'P.B.M'],
['P', 'P.C', 'P.C.L'],
['A', 'A.C', 'A.C.L3']
]