如何从数组中获取唯一值?

时间:2018-04-03 13:48:04

标签: javascript arrays lodash

var years = this.api().columns(2).data().toArray().sort();
console.log(years + " before uniq");
var duplicateFreeYears = Array.from(new Set(years));
const uniqueTopicList = _.uniq(years)
console.log("||" + duplicateFreeYears + " after duplicateFreeYears||");
console.log("||" + uniqueTopicList + " after uniqueTopicList||");

我在uniq之前和之后的数据都是一样的。

2016,2016,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015 before uniq


||2016,2016,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015 after duplicateFreeYears||


||2016,2016,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015,2015 after uniqueTopicList||

我仍然获得相同的数据

2 个答案:

答案 0 :(得分:0)

该函数为您提供更新数组的重复版本。

您必须显示此重复数组:

var duplicateArray = _.uniq(years);
console.log(duplicateArray + " after uniq");

答案 1 :(得分:-1)

通过将其转换为集合然后再将数组转换为数组,可以解决此问题:

Array.from(new Set(years));