Skip to content

Instantly share code, notes, and snippets.

@anuragkapur
Created December 24, 2019 01:16
Show Gist options
  • Save anuragkapur/4da97b7f87d6c25862412db8419d8916 to your computer and use it in GitHub Desktop.
Save anuragkapur/4da97b7f87d6c25862412db8419d8916 to your computer and use it in GitHub Desktop.
Example showcasing reduce function
// For the data set given below, find room which is false for all suspects (objects in the newDevelopment array)
const newDevelopment = [
{
name: 'Miss Scarlet',
present: true,
rooms: [
{kitchen: false},
{ballroom: false},
{conservatory: true},
{'dining room': true},
{'billiard room': false},
{library: true}
]
},
{
name: 'Reverend Green',
present: true,
rooms: [
{kitchen: true},
{ballroom: false},
{conservatory: false},
{'dining room': false},
{'billiard room': true},
{library: false}
]
},
{
name: 'Colonel Mustard',
present: true,
rooms: [
{kitchen: false},
{ballroom: false},
{conservatory: true},
{'dining room': false},
{'billiard room': true},
{library: false}
]
},
{
name: 'Professor Plum',
present: true,
rooms: [
{kitchen: true},
{ballroom: false},
{conservatory: false},
{'dining room': true},
{'billiard room': false},
{library: false}
]
}
];
function intersection(rooms1, rooms2) {
const intersection = [];
rooms1.forEach(room => {
if (rooms2.includes(room)) {
intersection.push(room);
}
});
return intersection;
}
const listOfListOfRooms = [];
newDevelopment.forEach(suspect => {
const listOfRooms = suspect.rooms
.filter(room => Object.values(room).includes(false))
.flatMap(room => Object.keys(room));
listOfListOfRooms.push(listOfRooms);
});
console.log(listOfListOfRooms.reduce(intersection));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment