Could someone try to help me understanding what is going on in the intermediate solution of Sorted Union?
I am having difficulties understanding we have concat going on inside a reduce… Also… stupid question but how are arrA and arrB different? How should I read them?
function uniteUnique(arr1, arr2, arr3) {
var newArr;
//Convert the arguments object into an array
var args = Array.prototype.slice.call(arguments);
//Use reduce function to flatten the array
newArr = args.reduce(function(arrA,arrB){
//Apply filter to remove the duplicate elements in the array
return arrA.concat(arrB.filter(function(i){
return arrA.indexOf(i) === -1;
}));
});
return newArr;
}
// test here
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
concat() takes two or more arrays, merge them and returns a new merged array.
First two parameters or reduce() are accumulator and currentArrayItem (as no default accumulator value is provided initial value of accumulator is the first element of the initial array).
Reduce works by taking accumulator and currentArrayItem, doing some stuff and returning a new accumulator which is then used on the next iteration.
Therefore reduce() part should be read:
newArr = args.reduce(function(accumulator, currentArrayItem) {
// Take accumulator and merge it...
return accumulator.concat(
// ...with currentArrayItem, but before that filter out...
currentArrayItem.filter(function(i) {
// ...values that are already in the accumulator
return accumulator.indexOf(i) === -1;
})
);
// return new merged array and use it as the accumulator
// on the next iteration or return it if this was the last element
// of args array
});