1、交换数组指定位置元素位置
例如: [1 ,2, 3, 4] ===> [1, 2, 4, 3]
// x , y是要交换元素的位置(index+1)
function arrIndexExchange(array, x, y){
array.splice(x - 1, 1, ...array.splice(y - 1, 1, array[x - 1]));
return array;
};
2、数组去重,想到的就是ES6的 new Set()
let array=[1,2,3,1,'1']
[...new Set(array)]
(4) [1, 2, 3, "1"]
3、使用 array.reduce 来统计一个数组中数字重复出现的次数
const arr =[1,2,3,1,4,45,4,67,6,823,8,8];
const statistics = arr.reduce((tally,item)=>{
tally[item]? tally[item]++ : tally[item] = 1;
return tally;
},{});
console.log(statistics); // {1: 2, 2: 1, 3: 1, 4: 2, 6: 1, 8: 2, 45: 1, 67: 1, 823: 1}