laukCoder laukCoder - 1 month ago 6
Javascript Question

Using reduce to remove like elements

https://www.freecodecamp.com/challenges/sorted-union

Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

I've solved this problem with this code:

function uniteUnique(arr) {
var arg = arguments[0];
var newArr = [];
var i = 0;
var matchFound = false;

//start newArr with each element of arg
while(i < arg.length){
newArr.push(arg[i++]);
}

//iterate over the argument sets
for(i = 1; i < arguments.length; i++){
//iterate over the argument set values
for(var j = 0; j < arguments[i].length; j++){
//compare each value with arg values
for(var k = 0; k < arg.length; k++){
if(arg[k] === arguments[i][j]){
matchFound = true;
}
}
if(!matchFound){
//if no comparison was found add element to newArr
newArr.push(arguments[i][j]);
}
//reset matchFound
matchFound = false;
}
}

return newArr;
}

// Function Call
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]); //returns [1, 3, 2, 5, 4]


My question is how would I solve this problem using .reduce and are there other ways that I could clean this up a bit to make it easier to read?

Answer

You could combine reduce with filter.

var uniteUnique = [[1, 3, 2], [5, 2, 1, 4], [2, 1]]
.reduce( (a, b) => {
  return a.concat(b)
})
.filter( (x, idx, arr) => arr.indexOf(x) == idx )

console.log(uniteUnique)

But there is actually no need to use reduce at all.

You could just

var uniteUnique = [1, 3, 2].concat([5, 2, 1, 4], [2, 1])
    .filter( (x, idx, arr) => arr.indexOf(x) == idx )

console.log(uniteUnique)