js 两个数组比较进行排序数组
原结构
arr1: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] //key
arr2:[ 2, 10, 6, 2, 0, 0, 0, 2, 0, 1 ]//数量
排序后:
arr1: [ 4, 5, 6, 8, 9, 0, 3, 7, 2, 1 ] //key
arr2:[ 0, 0, 0, 0, 1, 2, 2, 2, 6, 10 ] //数量
1【js内置组件方式】
//排序逻辑 let arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]; let arr2 = [2, 10, 6, 2, 0, 0, 0, 2, 0, 1, ]; let arrs = []; arrs = arr1.map((ee, ii) => { //合并成一个数组 return [ee, arr2[ii]]; }); arrs.sort((xx, yy) => { //排序 if (xx[0] > yy[0]) { return 1; } else { return -1; } }); for (let var1 in arrs) { //排序后筛分成独立数组 arr111.push(arrs[var1][1]); arr222.push(arrs[var1][0]); }
2【原生方式】
let arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]; let arr2 = [2, 10, 6, 2, 0, 0, 0, 2, 0, 1, ]; let a1 = []; let a2 = []; let obj = {}; // 合成队象 for (let i = 0; i < arr1.length; i++) { obj[arr1[i]] = arr2[i]; } let arr = Object.keys(obj); // 冒泡排序 for (let i = 0; i < arr.length; i += 1) { for (let j = 0; j < arr.length - i; j += 1) { if (obj[arr[j]] < obj[arr[j + 1]]) { [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } // 提取成数组 for (const item of arr) { a1.push(item); a2.push(obj[item]); } console.log(a1); console.log(a2);
823 Views