去重:
function duplicate(arr){ let obj = {}; for(let i=0;i<arr.length;i++){ let item = arr[i]; if(typeof obj[item] !== 'undefined'){ arr[i]=arr[arr.length-1]; arr.length --; i--; } obj[item]=item } obj=null; //清除内存 return arr } let list= [1,2,6,3,6,4,4,5]; console.log(duplicate(list)) // [1, 2, 6, 3, 5, 4]
方法2: es6 的 Set()方法
let arr= [1,2,6,3,6,4,4,5] let s = [...new Set(arr)]; console.log(s) //[1, 2, 6, 3, 5, 4]
最大值,最小值:
let arr =[1, 2, 6, 3, 5, 4]; Math.max.apply(null,arr) //6 Math.max(...arr) //6 -es6的解构赋值
最小值:
let arr =[1, 2, 6, 3, 5, 4]; Math.min.apply(null,arr) //1 Math.min(...arr) //1 -es6的解构赋值
升序:
let arr = [1, 2, 6, 3, 5, 4]; let newArr = arr.sort((a,b)=>a-b) console.log(newArr) // [1,2,3,4,5,6]
降序:
let arr = [1, 2, 6, 3, 5, 4]; let newArr = arr.sort((a,b)=>b-a) console.log(newArr) //[6,5,4,3,2,1]
乱序:
let arr = [1, 2, 6, 3, 5, 4]; //低效乱序 let newArr = arr.sort((a,b)=>Math.ramdom()>0.5? -1 :1) //高效乱序 function shuffle(originalArr) { let arr = [...originalArr]; for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x); return arr; } let newArr = shuffle(arr)