在lodash中使用.uniq函数时如何指定[isSorted = true]?

时间:2014-01-29 04:53:58

标签: javascript lodash

我有以下数组:

var tst = 
[
 {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"11"},
 {"topicId":1,"subTopicId":2,"topicName":"a","subTopicName":"22"},
 {"topicId":1,"subTopicId":3,"topicName":"a","subTopicName":"33"},
 {"topicId":2,"subTopicId":x,"topicName":"b","subTopicName":"xx"},
 {"topicId":3,"subTopicId":y,"topicName":"c","subTopicName":"yy"}
]

我想要做的是使用_lodash

的_.uniq函数
_.uniq(array, [isSorted=false], [callback=identity], [thisArg])

创建这个:

var t = 
[
 {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"11"},
 {"topicId":2,"subTopicId":x,"topicName":"b","subTopicName":"xx"},
 {"topicId":3,"subTopicId":y,"topicName":"c","subTopicName":"yy"}
]

我知道我可以使用以下内容执行此操作,但我不确定我是否理解这与我在文档中看到的函数定义相匹配:

var t = _.uniq(tst, 'topicId');

但是由于我的数组总是排序,那么我如何使用选项[isSorted = true]。也是'topicId' 被视为排序的参数?

1 个答案:

答案 0 :(得分:2)

你的问题有答案! 来自:http://lodash.com/docs#uniq

_.uniq(array, [isSorted=false], [callback=identity], [thisArg])

因此,在您的示例中,您将按如下方式使用它:

var t = _.uniq(tst, true, 'topicId');