I have an array of objects - say, NFL teams. Each object (team) has a property - array of first names of team players.
var nflTeams = [
{ name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true },
{ name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false },
{ name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false },
{ name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false },
];
Expected result - an object with an occurrence of first names: {'Joe': 1, 'Jimmy': 2, 'Jalen': 1 ....}
My goal is to achieve it through the use of Underscore methods such as _.map(), _.flatten(), _.reduce() all chained together using _.chain().
My current attempt miserably fails at _.reduce() stage:
var firstNameOccurence = { '{players firstName}': 0 };
firstNameOccurence = _.chain (nflTeams)
.map(function(team) {return team.playersFirstNames})
.flatten()
.reduce(function(newObject, firstName){
console.log ('we have a first name of a player', firstName);
return newObject[firstName] = 1 ? !newObject[firstName] : newObject[firstName] += 1;
}, {})
.value();
Now it gives me just a boolean value of true. My ideal is try to use ternary expression because it looks more elegant. I tried using official Underscore documentation and some examples like this, this and this.