JSFiddle - React, Tailwind, and code Playground

by samonela

JavaScript

const arr = [
    {key1: [{key2: {id: 1, name: 'a'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}, {key2: {id: 3, name: 'c'}}]},
    {key1: [{key2: {id: 1, name: 'b'}}, {key2: {id: 3, name: 'c'}}]},
    {key1: [{key2: {id: 3, name: 'b'}}, {key2: {id: 3, name: 'a'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}, {key2: {id: 3, name: 'c'}}]}
];

const counts = {};
for (let category of arr) {
    for (let subCategory of category.key1) {
    	const countKey = JSON.stringify(subCategory.key2)
      counts[countKey] = (counts[countKey] || 0) + 1;
    }
}
const dedupedArrWithCount = [];
for(let key in counts) {
	const obj = JSON.parse(key);
  dedupedArrWithCount.push(Object.assign(obj, {count: counts[key]}));
}

console.log(dedupedArrWithCount);