隨機數(shù)組洗牌
function foo(arr){
var newarr = arr.slice();
for(let i=0,len = arr.length;i<len;i++){
let index = Math.floor(Math.random() * len);
[newarr[i], newarr[index]] = [newarr[index], newarr[i]];
}
return newarr;
}
console.log(foo([1, 2, 3, 4, 5, 6, 7]));
簡單的日期字符串排序
var date = ['2010-03-19', '2020-04-01', '2015-09-07', '2015-09-08'];
var aa =date.sort((a,b)=> Date.parse(b) - Date.parse(a) );
console.log(aa);
遞歸實現(xiàn)數(shù)組扁平化
function flatArr(arr){
let tempArr=[];
arr.forEach(item => {
if (Array.isArray(item)){
tempArr= tempArr.concat(flatArr(item));
}else{
tempArr.push(item);
}
});
return tempArr;
}
console.log(flatArr([1,2,[3,4,[5,[[6]]]]]));
極簡版數(shù)組扁平化
[1,2,3,[4,5,[6,[[7]]]]].flat(Infinity);
記錄數(shù)組項重復(fù)次數(shù)
var arr = ['張三', '張三', 'zzz', '歷史', 'zzz', 'zzz'];
function getRepeatTimes() {
var Obj = {};
arr.forEach(item => {
Obj[item] = (Obj[item] + 1) || 1; //Obj[item]如不存在,+1為NaN
})
return Obj;
}
console.log(getRepeatTimes(arr))
冒泡排序
function arrSort(arr = []) {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let k = 0; k < len - 1 - i; k++) {
if (arr[k] > arr[k + 1]) {
[arr[k], arr[k + 1]] = [arr[k + 1], arr[k]];
}
}
}
return arr;
}
console.log(arrSort([5, 3, 6, 1, 9, 4, 9, 4, 8, 7, 8, 6, 2]));
快速排序(適合數(shù)據(jù)量大的排序)
function quickSort(arr) {
if (arr.length <= 1) { return arr; }
var midIndex = Math.floor(arr.length / 2);
var mid = arr.splice(midIndex, 1)[0]; //取得中間基準(zhǔn)并刪除掉
var left = [],right = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] <= mid) { //把基準(zhǔn)兩邊的數(shù)據(jù)分別存放到不同分區(qū)
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([mid], quickSort(right));
}
console.log(quickSort([4, 8, 7, 3, 5, 1, 2, 9, 0, 7, 5]))