Search⌘ K

Solution to Sub-task: Reduce

Explore how to apply the reduce method in JavaScript to iterate over nested arrays and filter mutual users while excluding specific values. This lesson helps you understand array transformations and filtering techniques to aggregate mutual connections.

We'll cover the following...

Reduce

Here, take each element of the object and convert the array of two arrays into an array of mutual users.

Node.js
// Reduce
function reducer (grouped_obj) {
for (x in grouped_obj){
var arr1 = grouped_obj[x][0];
var arr2 = grouped_obj[x][1];
// take intersection of the two and assign to property name x
grouped_obj[x] = arr1.filter(i => arr2.indexOf(i) !== -1
&& x.charAt(0) !== i
&& x.charAt(1) !== i
)
}
return grouped_obj;
// return an object {(man,friend): [Friends]}
}
var grouped_obj = {
'AB': [ [ 'B', 'C', 'D' ], [ 'A', 'C', 'D', 'E' ] ],
'AC': [ [ 'B', 'C', 'D' ], [ 'A', 'B', 'D', 'E' ] ],
'AD': [ [ 'B', 'C', 'D' ], [ 'A', 'B', 'C', 'E' ] ],
'BC': [ [ 'A', 'C', 'D', 'E' ], [ 'A', 'B', 'D', 'E' ] ],
'BD': [ [ 'A', 'C', 'D', 'E' ], [ 'A', 'B', 'C', 'E' ] ],
'BE': [ [ 'A', 'C', 'D', 'E' ], [ 'B', 'C', 'D' ] ],
'CD': [ [ 'A', 'B', 'D', 'E' ], [ 'A', 'B', 'C', 'E' ] ],
'CE': [ [ 'A', 'B', 'D', 'E' ], [ 'B', 'C', 'D' ] ],
'DE': [ [ 'A', 'B', 'C', 'E' ], [ 'B', 'C', 'D' ] ]
}
console.log(reducer(grouped_obj));

In ...