javascript 从数组中获取不同的元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 从数组中获取不同的元素相关的知识,希望对你有一定的参考价值。

const years = [2016, 2017, 2017, 2016, 2019, 2018, 2019];

// ES5
const distinct = (value, index, self) => {
	return self.indexOf(value) === index;
};

var distinctYears = years.filter(distinct); //return [2016, 2017, 2019, 2018]
distinctYears

// ES6
var distinctYears = [...new Set(years)];
distinctYears
// It will work on primitive values only, need some more customized methods if an array of dates

// The following code will not work as Set compares objects by reference
const dates = [
	new Date(2018, 8, 1),
	new Date(2018, 9, 1),
	new Date(2018, 8, 1),
	new Date(2018, 9, 1)
];
[...new Set(dates)]

以上是关于javascript 从数组中获取不同的元素的主要内容,如果未能解决你的问题,请参考以下文章