-3

I have array

let arr = ["hello","Hey","Moon","Hey,"Turtle"];

I need to count how many times an element appears in the array. the result need to be like this:

"Hello":1
"hey":2
"Moon":1
"Turtle":1

Thanks

Eddie
  • 26,593
  • 6
  • 36
  • 58
Baruch Mashasha
  • 951
  • 1
  • 11
  • 29
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Aug 08 '19 at 13:06

2 Answers2

0

Really simple - use reduce like so to return an object:

let arr = ["hello", "Hey", "Moon", "Hey", "Turtle"];

const res = arr.reduce((a, c) => (a[c] = (a[c] || 0) + 1, a), {});

console.log(res);

Do note that order won't be guaranteed.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can use Array#reduce to aggregate lists to single values.

var arr = ["hello", "Hey", "Moon", "Hey", "Turtle"];

function checkCount(list, itemToFind) {
  return list.reduce(function(count, item) {
    return count + (item === itemToFind ? 1 : 0);
  }, 0);
}

console.log(checkCount(arr, "Hey"));

You can also return an object that contains each property and how many times it has been found so far.

var arr = ["hello", "Hey", "Moon", "Hey", "Turtle"];

function checkCount(list) {
  return list.reduce(function(result, item) {
    result[item] = item in result ? result[item] + 1 : 1;
    return result;
  }, {});
}

console.log(checkCount(arr));
nick zoum
  • 7,216
  • 7
  • 36
  • 80