Y
Y
yevkov2019-04-02 22:08:00
JavaScript
yevkov, 2019-04-02 22:08:00

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

1 answer(s)
S
Stockholm Syndrome, 2019-04-02
@yevkov

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), {});

or so
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 question

Ask a Question

731 491 924 answers to any question