Home > database >  Javascript - Compare and count reoccurrences of nested array and display number of reoccurences of e
Javascript - Compare and count reoccurrences of nested array and display number of reoccurences of e

Time:10-12

I am trying to count the occurrences of the given array and generate the desire output. I tried for loops, reduce and filter but always cant display the output i want.

for eg:

var array = [
            0: ["101", 1],
            1: ["101", 1],
            2: ["101", 1],
            3: ["101", 10],
            4: ["101", 10]
            ]

array.reduce(function (acc, curr) {
 return acc[curr] ?   acc[curr] : acc[curr] = 1, acc
}, {});

Desire output

["101", 1] = 3
["101", 10] = 2

CodePudding user response:

1) You can get the count of the unique property using Map and null coalescing operator

var array = [
  ["101", 1],
  ["101", 1],
  ["101", 1],
  ["101", 10],
  ["101", 10],
];
const map = new Map();

const convertToString = (arr) => `${arr[0]}|${arr[1]}`;
for (let arr of array) {
  const key = convertToString(arr);
  map.set(key, (map.get(key) ?? 0)   1);
}

for (let [k, v] of [...map.entries()]) {
  console.log(`[${k.split("|")}] = ${v}`);
}

2) Without null coalescing operator

var array = [
  ["101", 1],
  ["101", 1],
  ["101", 1],
  ["101", 10],
  ["101", 10],
];
const map = new Map();

const convertToString = (arr) => `${arr[0]}|${arr[1]}`;
for (let arr of array) {
  const key = convertToString(arr);
  if (map.has(key)) map.set(key, map.get(key)   1);
  else map.set(key, 1);
}

for (let [k, v] of [...map.entries()]) {
  console.log(`[${k.split("|")}] = ${v}`);
}

  • Related