The data describes cycling activities (key1) and chunks of them (key2). In total there are around 1,000 key1 objects and arrays under key1 are 1-100 long.
- Is there a simpler, more semantic, faster, or otherwise better way than to use two nested map in step 1?
- I realise that step 3 is longer than it should be and there has to be a better way to do it. How can step 3 be improved?
// Original array
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'}}]}
];
console.log(arr);
// Step 1: Extract meaningful information from original array
const arrOfArrOfObj = arr
.map(category => category.key1
.map(subCategory => (
{
id: subCategory.key2.id,
name: subCategory.key2.name
}
)
)
);
console.log(arrOfArrOfObj);
// Step 2: Make the array one dimensional
const arrOfObj = [].concat(...arrOfArrOfObj);
console.log(arrOfObj);
// Step 3: Remove duplicates and count object occurrences.
let dedupedArrWithCount = [];
l = arrOfObj.length;
for (let i = 0; i < l; i++) {
let objExists = false;
for (let j = 0; j < dedupedArrWithCount.length; j++) {
// Two objects are identical if their ids are identical.
if (arrOfObj[i].id === dedupedArrWithCount[j].id) {
objExists = true;
dedupedArrWithCount[j].count += 1;
}
}
if (!objExists) {
dedupedArrWithCount.push({
id: arrOfObj[i].id,
name: arrOfObj[i].name,
count: 1
})
}
}
console.log(dedupedArrWithCount);