-1

I have this array: array

In this array I have at least 3x 'a' or 2x 'c'. Is it possible to get the number of times that a character is duplicated?

Alien18
  • 17
  • 6
  • 1
    Have you tried anything? – Robo Robok Oct 13 '22 at 22:48
  • I have. But I'm only able to get the characters in each array, not in all of them. – Alien18 Oct 13 '22 at 22:49
  • 2
    You can flatten your array with `myArray.flat()` and then use your approach :) – Robo Robok Oct 13 '22 at 22:51
  • 1
    Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) And use flat() as @RoboRobok suggested. – Yogi Oct 13 '22 at 22:55
  • 2
    "count the number of occurrences" is probably a more appropriate description of what you are trying to do than "length of a duplicated value" – Wyck Oct 13 '22 at 22:56

1 Answers1

1

One possible solution is to use reduce() and forEach():

const myArray = [
  ["a", "b", "c"],
  ["a", "n", "c"],
  ["e", "f", "g"],
  ["i", "a", "l"],
];
const occurrences = myArray.reduce((count, currentValue) => {
  currentValue.forEach((value) => {
    count[value] ? ++count[value] : (count[value] = 1);
  });
  return count;
}, {});

console.log(JSON.stringify(occurrences));
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Strictly speaking the above counts the occurrences of a letter but if you use count[value] = 0 instead of count[value] = 1 it will count the number of duplicates.

Another approach is to flatten the array first using flat() and then use reduce() the same way as used above. Again if you set count[value] = 0 you will count the duplicates, not occurrences, but essentially that's the same thing.

const myArray = [
  ["a", "b", "c"],
  ["a", "n", "c"],
  ["e", "f", "g"],
  ["i", "a", "l"],
];
const occurrences = myArray
  .flat()
  .reduce(
    (count, value) => (
      count[value] ? ++count[value] : (count[value] = 1), count
    ),
    {}
  );

console.log(JSON.stringify(occurrences));
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mushroomator
  • 6,516
  • 1
  • 10
  • 27