const beatles = [
{
name: 'John'
instrument: 'guitar',
status: 'dead'
},
{
name: 'Paul',
instrument: 'bass',
status: 'living'
},
{
name: 'George',
instrument: 'guitar',
status: 'dead'
},
{
name: 'Ringo',
instrument: 'drums',
status: 'living'
},
];
How many members of The Beatles are living?
const isLiving = function(beatle) {
return beatle.status == 'living';
}
const livingBeatles = beatles.filter(isLiving).length;
console.log(livingBeatles); // 2
Are there any living members of The Beatles that play drums?
const isLivingAndDrummer = function(beatle) {
return beatle.status == 'living' && beatle.instrument == 'drums';
}
const livingBeatleDrummers = beatles.some(isLivingAndDrummer);
console.log(livingBeatleDrummers); // true
Which members of The Beatles played stringed instruments?
const hasStringedInstrument = function(accumulator, beatle) {
if (beatle.instrument == 'guitar' || beatle.instrument == 'bass') {
return accumulator = [...accumulator, beatle.name];
} else {
return accumulator;
}
}
const playedStringed = beatles.reduce(hasStringedInstrument, []);
console.log(playedStringed); // ['John', 'Paul', 'George']