参考资料html
数组去重方法面试
[TOC]bash
// 输入数据
const input = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]
// 输出数据
expect = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
// 附加条件 最好不要超过五行
复制代码
const ary = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10]
console.log('ary', [... new Set(ary.flat(Infinity))].sort((a, b) => a - b))
复制代码
- flat(Infinity) 不知道怎么办??
const flatten = input => {
result = []
input.forEach(v => Array.isArray(v) ? result = result.concat(flatten(v)) : result.push(v))
return result
}
复制代码
归并方法:reduceui
(1行 不过太难于理解了)spa
reduce的第二个参数:做为归并基础的初始值code
const flatten = input => input.reduce((prev, next) => prev.concat(Array.isArray(next) ? flatten(next) : next), []);
复制代码
ES6:...
扩展运算符htm
5行代码对象
const flatten = input => {
while(input.some(v => Array.isArray(v))){
input = [].concat(...input)
}
return input
}
复制代码
toString法blog
一行代码
只适用于数组元素所有为数字的状况下
const flatten = ary => ary.toString().split(",").map(v => +v)
复制代码
const uniq = input => input.reduce((cur, next) => cur.indexOf(next) !== -1 ? cur : [...cur, next], [])
复制代码
对象键值 + reduce 去重
速度最快, 占空间最多(空间换时间)
该方法执行的速度比其余任何方法都快, 就是占用的内存大一些。 现思路:新建一js对象以及新数组,遍历传入数组时,判断值是否为js对象的键, 不是的话给对象新增该键并放入新数组。 注意点:判断是否为js对象键时,会自动对传入的键执行“toString()”, 不一样的键可能会被误认为同样,例如n[val]-- n[1]、n["1"]; 解决上述问题仍是得调用“indexOf”。*/ 复制代码
const obj = {}
const uniq = input => input.reduce((cur, next) => obj[next] ? cur : obj[next] = true && [...cur, next], [])
复制代码
排序相邻去重
一行搞定排序 + 去重
const uniq = input => input.sort((a, b) => a > b).reduce((cur, next) => cur[cur.length - 1] === next ? cur : [...cur, next], [])
复制代码
数组下标法
const uniq = input => input.reduce((cur, next, i) => input.indexOf(next) !== i ? cur : [...cur, next], [])
复制代码
Set去重
const uniq = input => [... new Set(input)]
复制代码