Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript group by and count function

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading