Using javascript array.reduce to remove duplicates

advertisements

I am new to javascript and I am having a bit of challenge learning it myself from web tutorials. Please help me to solve the problem below.

Problem:

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.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

Use only Array.reduce to solve this ! This is what your solution should look like:

function unite(arr1, arr2, arr3) {
  return arr1;
}

unite([1, 2, 3], [5, 2, 1, 4], [2, 1]);

I am not able to understand how I can use reduce here. All the internet examples are so easy compared to this. https://www.airpair.com/javascript/javascript-array-reduce http://adripofjavascript.com/blog/drips/boiling-down-arrays-with-array-reduce.html

My wrong solution:

function arrayDiff(resultArray, element){
    var idx = anotherArray.indexOf(element);
    if(idx != -1){
        resultArray.push(element);
        return resultArray;
    }
}

function unite(arr1, arr2, arr3) {
    var arr = [];
    var r1 = arr1.reduce(arrayDiff);
    var r2 = arr2.reduce(arrayDiff);
    var r3 = arr3.reduce(arrayDiff);
    arr.concat(r1).concat(r2).concat(r3);
    return arr;
}

r = unite([1, 2, 3], [5, 2, 1, 4], [2, 1]);
console.log(r);

Error: ReferenceError: anotherArray is not defined


To handle multiple array parameters, you can use arguments. Thanks to that, your function can take N parameters, it is more generic.

Then, you can flat all your array parameters, and start to reduce your data. When you will reduce our array, you will create a new array by excluding redundant data. So you will start with an empty array, and you will populate it through the reduce process.

  function unite(){
    //Flat array arguments, then process to reduce data
    return [].concat.apply([], arguments).reduce(function(result, current){
      //If my result array doesn't get current element
      return result.indexOf(current) === -1
      //concat current element to result and return it
      ? result.concat(current)
      //Otherwise, just return actual result array
      : result;
    }, []);
  }

  var array = unite([1,2], [1,6,2,3], [4,5]);

  console.log(array);
  //[1,2,6,3,4,5]

EDIT 06/02/2017:

Now, you can use the spread operator in order to handle multiple parameters, by destructuring the assignment for example. Moreover, we can improve performance by using the indexOf() operation with the bitwise operator ~.

function unite(...data) {
  return [].concat.apply([], data).reduce((result, current) => {
    return ~result.indexOf(current)
    ? result
    : result.concat(current)
  }, []);
}

console.log(unite([1,2,3], [1, 4, 4, 5, 6]));