Max Lynn Max Lynn - 4 months ago 11
AngularJS Question

The best way to remove duplicate strings in an array

We have managed to create the script below to remove any duplicate strings from an array however it is important that we keep the order of the array for when angular loops through them on an ng-repeat.

scope.feedback = _.map(_.pluck(item.possibleAnswers, 'feedback'), function (element, index, collection) {
return collection.slice(0, index).indexOf(element) === -1 ? element : '';
});


This code above works however we feel like there must be a more simple solution to our problem than this. Has anyone else had a similar problem and come up with a better solution?

Answer

Variant with reduce https://jsfiddle.net/58z7nrfy/1/

var a = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];

var b = a.reduce(function(p,c,i,a){
  if (p.indexOf(c) == -1) p.push(c);
  else p.push('')
  return p;
}, [])
console.log(b)

[1, 2, 3, "", "", "", "", "", "", 4, 5, "", 12, "", 23, "", ""]