My attempt was to count the occurrences of the same values in objects and arrays. The goal was to display the initial numbers that appear in arrays within an object. Here is my flawed code along with an example case:
let index = {};
let result = [];
const arrayList = [{
"code": 101,
"name": "banana",
"price": 1000
}, {
"code": 4,
"name": "blueberries",
"price": 3000
}, {
"code": 900,
"name": "apple",
"price": 300
}];
// Array containing user choices
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];
userChoose.forEach(choice => {
arrayList.forEach(item => {
let key = choice;
if (key in index) {
index[key].count++;
} else {
let newEntry = {
id: item.code,
count: 1
};
index[key] = newEntry;
result.push(newEntry);
}
})
});
console.log(result);
The output does not match the expected result which should look like this:
// Desired final result:
[
{
"id": 900,
"count": 2
},
{
"id": 101,
"count": 11
}
]