let arr = [1,23,[121,1,53,[234,342,324,[234,432],234]]]
快速实现
let arr1 = arr.flat(Infinity) //降维
let arr2 = Array.from( new Set(arr1)) //去重,转为数组
let arr3 = arr2.sort((a,b)=>(a-b)) // 排序
console.log(arr3)
数组降维方法
1:递归
var arr1 = [[0, 1], [2, 3], [4, 5]];
var arrFn=(arr)=> ( [].concat( ...arr.map(x => Array.isArray(x) ? arrFn(x) : x) ) )
arrFn(arr1)
var arr = [[1, 2, 3], 4, 5, 6, [[7]], []] //多维数组
const res = []
function fn(array) {
for (var i of array) {
if (Array.isArray(i)) {
fn(i)
} else {
res.push(i)
}
}
}
fn(arr)
console.log(res
2:Array.flat()
const newArr = arr.flat() //参数为展开嵌套深度(number类型)
参数:
Infinity 展开任意深度的嵌套数组
数组去重
1:filter方法
function fn(arr) {
let newArr = arr.filter((item, index) => {
return arr.indexOf(item, 0) === index
})
return newArr
}
console.log(fn(arr))
2:set方法
let arr = [1,22,1,3,[2,1,32,[1,3,43,24,23532,4,32],1,3]]
let newArr = Array.from( new Set(arr)) //去重,转为数组
let newArr = [...new Set(arr)] //去重,转为数组
数组排序
1:sort
let arr = [1, 4, 6, 7, 3, 5, 8];
let arr1 = arr.sort((a,b)=>(a-b)) //a-b 升序 b-a 降序
2:冒泡排序
let arr = [1, 4, 6, 7, 3, 5, 8];
let max = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) { // > 升序 < 降序
max = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = max;
}
}
}
console.log(arr);
3:选择排序
let arr = [1, 4, 6, 7, 3, 5, 8];
var temp;
for(var i=0;i<arr.length-1;i++){
for(var j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
console.log(arr)
4:希尔排序
function xier(arr){
var interval = parseInt(arr.length / 2); //分组间隔设置
while(interval > 0){
for(var i = 0 ; i < arr.length ; i ++){
var n = i;
while(arr[n] < arr[n - interval] && n > 0){
var temp = arr[n];
arr[n] = arr[n - interval];
arr[n - interval] = temp;
n = n - interval;
}
}
interval = parseInt(interval / 2);
}
return arr;
}
console.log(xier([12,9,38,44,7,98,35,59,49,88,38]))
补充 对象数组排序
//对象数组排序
var arr = [
{name:'syy',age:0},
{name:'wxy',age:18},
{name:'slj',age:8},
{name:'wj',age:20}
];
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;//升序,降序为value2 - value1
}
}
arr.sort(compare('age'))
console.log(arr)
标签:arr,console,interval,降维,let,数组,var,排序
From: https://blog.51cto.com/u_16202629/6890948