Answer the question
In order to leave comments, you need to log in
How to find out the number of identical values in an array of objects?
An array of objects of the form
[{a: 1, b: 2, c: 3}, {a: 1, b: 4, c: 3}] is given. It is
necessary to find out the number of repetitions of each value.
That is, at the output
a = 2;
b = 1;
c = 2;
Answer the question
In order to leave comments, you need to log in
Object.entries(data.reduce((acc, curr) => {
for (let key in curr) {
acc[key] = acc[key] || {values: [curr[key]], count: 0};
if (acc[key].values.includes(curr[key])) {
acc[key].count++;
} else {
acc[key].values.push(curr[key]);
}
}
return acc;
}, {})).reduce((acc, [key, {count}]) => ((acc[key] = count), acc), {});
data.reduce((acc, curr) => {
for (let key in curr) {
let item = acc.find((item) => item.key === key);
if (!item) {
item = {key, values: [curr[key]], count: 0};
acc.push(item);
}
if (item.values.includes(curr[key])) {
item.count++;
} else {
item.values.push(curr[key]);
}
}
return acc;
}, []).reduce((acc, {key, count}) => ((acc[key] = count), acc), {});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question