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
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
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.
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));