Search This Blog

2023/09/10

Javascript Interview Question:counting number of matching objects within an array

Problem statement:
For array below containing fruits and their count for each
iteration of baskets for multiple baskets

const fruits = [
{ Apple: 4, Orange: 7, Grape: 3 },
{ Guava: 6, Lemon: 4, Banana: 8 },
{ Orange: 5, Pineapple: 7, Apple: 7 },
];

count total numbers of fruits by each type.

Code:
const fruits = [
{ Apple: 4, Orange: 7, Grape: 3 },
{ Guava: 6, Lemon: 4, Banana: 8 },
{ Orange: 5, Pineapple: 7, Apple: 7 },
];

let fruitCount = {};

fruits.forEach((item) => {
for (let fruit in item) {
if (fruitCount[fruit]) {
fruitCount[fruit] = fruitCount[fruit] + item[fruit];
} else {
fruitCount[fruit] = item[fruit];
}
}
});

console.log(fruitCount);

Output:
{
Apple: 11,
Orange: 12,
Grape: 3,
Guava: 6,
Lemon: 4,
Banana: 8,
Pineapple: 7
}

No comments:

Post a Comment