删除数组中重复字符串的最佳方法 [英] The best way to remove duplicate strings in an array

查看:41
本文介绍了删除数组中重复字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们设法在下面创建了脚本,以从数组中删除所有重复的字符串.但是,重要的是,当ng-repeat上的角度循环通过数组时,我们必须保持数组的顺序.此外,我们希望其余元素保持相同的索引.

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?

推荐答案

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

这篇关于删除数组中重复字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆