Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from arrays using reduce

Tags:

javascript

I am trying to remove duplicates from a list of arrays. The way I was trying to do this is by using reduce to create an empty array that pushes all undefined indexes onto that array. I am getting errors though that

if(acc[item]===undefined){
      ^
TypeError: Cannot read property '1' of undefined

my function below:

function noDuplicates(arrays) {
  var arrayed = Array.prototype.slice.call(arguments);

  return reduce(arrayed, function(acc, cur) {
    forEach(cur, function(item) {
      if (acc[item] === undefined) {
        acc.push(item);
      }
      return acc;
    });
  }, []);
}

console.log(noDuplicates([1, 2, 2, 4], [1, 1, 4, 5, 6]));
like image 337
learninjs Avatar asked Dec 01 '22 11:12

learninjs


1 Answers

First concatenate the two arrays, next use filter() to filter out only the unique items-

var a = [1, 2, 2, 4], b = [1, 1, 4, 5, 6];
var c = a.concat(b);
var d = c.filter(function (item, pos) {return c.indexOf(item) == pos});
console.log(d);
like image 139
Shekhar Chikara Avatar answered Dec 05 '22 17:12

Shekhar Chikara