Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

javascript - 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. In addition, we want the remaining elements to keep the same index.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, "", ""]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...