一.使用Set
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
二.使用filter和indexOf
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]
filter
方法会遍历数组中的每个元素,并传入回调函数 (value, index, self)
。回调函数中,indexOf
方法用于检查当前元素在数组中的第一个索引位置是否与当前索引相同,如果相同,则表示该元素是第一次出现,保留在结果数组中。
三.使用reduce
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
reduce
方法接收两个参数,回调函数 (accumulator, currentValue)
和初始值 []
。回调函数中,includes
方法用于检查累加器数组 accumulator
是否已经包含了当前元素 currentValue
,如果不包含,则将该元素推入累加器数组中。