I use this function in JavaScript:
function groupByAndCount(data, ...keys) {
const {
length
} = keys;
return Object.values(data[keys[0]].reduce((acc, _, i) => {
const group = keys.map(key => data[key][i]);
(acc[JSON.stringify(group)] ??= [...group, 0])[length]++;
return acc;
}, {}));
}
const data = {
type: ["a", "a", "b", "c", "d", "a", "a", "b"],
program: ["P1", "P1", "P2", "P1", "P2", "P2", "P2", "P1"],
reference: ["ref1", "ref2", "ref3", "ref4", "ref5", "ref6", "ref7", "ref8"]
}
const result = groupByAndCount(data, "program", "type");
console.log(result);
It worked fine until today but now I get this error:
ERROR: Unexpected token (5:38)
Do you know how to solve this? I don’t understand it
I just understand that the "5" in "(5:38)" corresponds to the line 5:
(acc[JSON.stringify(group)] ??= [...group, 0])[length]++;
>Solution :
The "ERROR: Unexpected token (5:38)" is referencing the Nullish coalescing assignment (??=) operator. The error suddenly popping up could be due to running the code in a different environment.
This operator only assigns a value to a operand if that operand is null or undefined.
Try replacing the logic. It will look less beautiful but should work again.
if (!acc[JSON.stringify(group)]) {
acc[JSON.stringify(group)] = [...group, 0];
}
acc[JSON.stringify(group)][length]++;
I have not tested it myself but it should work.