数组去重:
var arr = [ 1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{a:1,b:2},{a:1,b:2} ]; //1 function unique(arr){ var obj = {} return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(typeof item + item) ? false : (obj[type item + item] = true) }) } //2 arr1 = [... new Set(arr)] //3 arr2 = Array.from(new Set(arr)) //4 let obj = {} arr.forEach(item => { obj[item] = 1 }) Object.keys(obj).map(o => Number(o))
数组扁平:
//1 function flatten(arr){ return arr.toString().split(',').map(item => { return Number(item) }) } //2 function flatten(arr){ return arr.join(',').split(',').map(item => { return parseInt(item) }) } //3 arr1 = arr.flat(Infinity) //4 function flatten(item){ return items.reduce((prev, current) => { return prev.concat(Array.isArray(current) ? flatten(current) : current ) }, []) }