Hello so this was the task on codewars that I was solving today:
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising.
Your task is to return an object (associative array in PHP) which includes the count of each coding language represented at the meetup .
For example, given the following input array:
var list1 = [
{ firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C' },
{ firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript' },
{ firstName: 'Ramon', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby' },
{ firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C' },
];
your function should return the following object:
{ C: 2, JavaScript: 1, Ruby: 1 }
Notes:
- The order of the languages in the object does not matter.
- The count value should be a valid number.
- The input array will always be valid and formatted as in the example above.
///////////////
So here is my solution:
function countLanguages(list) {
let count = {};
list.forEach(i => count[i.language] = (count[i.language] || 0) + 1);
return count;
}
It all seems very compact and simple but I can’t figure out the callback function and forEach method in general. So can someone explain this to me?