js从数组中删除重复项

2019-12-251313次阅读javascript
const array = [1, 1, 1, 3, 3, 2, 2];

// Method 1: Using a Set
const unique = [...new Set(array)];

// Method 2: Array.prototype.reduce
const unique = array.reduce((result, element) => {
  return result.includes(element) ? result : [...result, element];
}, []);

// Method 3: Array.prototype.filter
const unique = array.filter((element, index) => {
  return array.indexOf(element) === index;
});

 

上一篇: HTML中CSS类的顺序真的无关紧要  下一篇: Sass中@for循环  

js从数组中删除重复项相关文章