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]));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With