假如有这么个数组arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']
,如何去重?
方法一
let arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']; function unrepeated(arr) { const res = []; arr.forEach(e => { !res.includes(e) && res.push(e); }) return res; } unrepeated(arr);
方法二
let arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']; function unrepeated(arr) { return arr.filter((e,i) => arr.indexOf(e) === i); } unrepeated(arr);
方法三
let arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']; function unrepeated(arr) { const res = {}; arr.forEach(e => { !res[e] && (res[e]=null); }) return Object.keys(res); } unrepeated(arr);
方法四
let arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']; function unrepeated(arr) { const res = new Map(); arr.forEach(e => { !res.has(e) && res.set(e); // 不加判断,直接覆盖也行 // res.set(e); }) return Array.from(res.keys()); } unrepeated(arr);
方法五
let arr = ['shanghai','beijing', 'hangzhou', 'guangzhou','nanjing','beijing','shanghai']; function unrepeated(arr) { return [...new Set(arr)] } unrepeated(arr);