JavaScript 数组去重的多种方式
2018-02-24 本文已影响0人
一蓑烟雨任平生_cui
const animals = ["Dog", "Cat", "Mouse", "Horse", "Dog", "Rhino"];
1、Set Object
const animalsSet = new Set(animals);
const uniqueAnimals1 = [...animalsSet];
const uniqueAnimals2 = Array.from(animalsSet);
或一行搞定
const uniqueAnimals = [...new Set(animals)];
2、filter()
const uniqueAnimals = animals.filter(
(animal, i) => animals.indexOf(animal) === i
)
3、reduce() & includes()
const uniqueAnimals = animals.reduce((result, element) => (
result.includes(element) ? result : [...result, element]
), [])
4、reduce() & Object.values()
const uniqueAnimals = Object.values(animals.reduce((pre, cur) => {
pre[cur] = cur
return pre
}, {}))
5、forEach()
const uniqueAnimals = [];
animals.forEach(animal => {
if (!uniqueAnimals.includes(animal)) {
uniqueAnimals.push(animal)
}
});
6、indexOf
const uniqueAnimals = [];
for (let i = 0; i < animals.length; i++) {
if (!~uniqueAnimals.indexOf(animals[i])) {
uniqueAnimals.push(animals[i])
}
}
7、将出现过的元素通过键的形式添加到对象中
const has = {};
const uniqueAnimals = [];
for (let i = 0; i < animals.length; i++) {
if (!has[animals[i]]) {
has[animals[i]] = true;
uniqueAnimals.push(animals[i])
}
}
8、先排序,再判断
animals.sort();
const uniqueAnimals = [];
for (var i = 0; i < animals.length; i++) {
if(animals[i] !== uniqueAnimals[uniqueAnimals.length - 1]){
uniqueAnimals.push(animals[i]);
}
}