如何通过值对数组进行降序排序?
数组降序排序的实现方案
下面提供几种符合你需求的实现方式,涵盖原生API、手动循环排序和构建新数组的方法:
方法1:使用原生sort方法(最简洁)
JavaScript数组自带的sort方法可以快速实现排序,只需传入自定义比较函数指定降序规则:
let myArray = [10, 50, 30, 20, 40]; // 直接修改原数组,按数值降序排列 myArray.sort((a, b) => b - a); console.log(myArray); // 输出:[50, 40, 30, 20, 10]
如果不想修改原数组,可以先复制再排序:
let myArray = [10, 50, 30, 20, 40]; let newArray = [...myArray].sort((a, b) => b - a); console.log(newArray); // 输出:[50, 40, 30, 20, 10] console.log(myArray); // 原数组保持不变
方法2:手动实现选择排序(用for循环+if判断)
通过两层for循环手动找到最大值并交换位置,完全基于基础逻辑实现:
let myArray = [10, 50, 30, 20, 40]; // 外层循环控制已排序区域的边界 for (let i = 0; i < myArray.length; i++) { let maxIndex = i; // 内层循环遍历未排序区域,找到最大值的索引 for (let j = i + 1; j < myArray.length; j++) { if (myArray[j] > myArray[maxIndex]) { maxIndex = j; } } // 交换当前位置和最大值位置的元素 [myArray[i], myArray[maxIndex]] = [myArray[maxIndex], myArray[i]]; } console.log(myArray); // 输出:[50, 40, 30, 20, 10]
方法3:提取最大值构建新数组
通过循环筛选当前数组的最大值,逐步存入新数组,不修改原数组:
let myArray = [10, 50, 30, 20, 40]; let newArray = []; // 复制原数组到临时变量,避免破坏原数据 let temp = [...myArray]; while (temp.length > 0) { let currentMax = temp[0]; let maxIndex = 0; // 遍历临时数组找最大值 for (let i = 1; i < temp.length; i++) { if (temp[i] > currentMax) { currentMax = temp[i]; maxIndex = i; } } // 将最大值加入新数组,并从临时数组移除 newArray.push(currentMax); temp.splice(maxIndex, 1); } console.log(newArray); // 输出:[50, 40, 30, 20, 10] console.log(myArray); // 原数组保持不变
内容的提问来源于stack exchange,提问作者Alireza
相关产品推荐
相关产品推荐

