103
Create an object with the number of occurrences of the array elements
2021-06-23 - JavaScript
1// JS Tip of the Day
2// Create an object with the number of occurrences of the array elements
3
4const occurrences = arr => {
5 return arr.reduce((obj, item) => {
6 obj[item] = obj[item] ? obj[item] + 1 : 1;
7 return obj;
8 }, {});
9}
10
11occurrences(['Batman', 'Superman', 'Batman', 'Cyborg']);
12// { Batman: 2, Superman: 1, Cyborg: 1 }
13
#JStipoftheday