let array = [1, 2, 3, 4, 2, 3, 5, 6, 4];
let uniqueArray = [];
array.filter((value, index, self) => {
if (self.indexOf(value) === index) {
uniqueArray.push(value);
}
});
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5, 6]
使用 Array.prototype.filter
方法,然后在回调函数中检查每个元素是否在数组中第一次出现,如果是,则将其添加到 uniqueArray
数组中。
let array = [1, 2, 3, 4, 2, 3, 5, 6, 4];
let uniqueArray = Array.from(new Set(array));
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5, 6]
通过 Set
对象创建了一个不含重复值的集合,然后通过 Array.from
方法将其转换为数组。