猿问

按特定顺序对 JS 数值数组进行排序

我有一个数组[1, 85, -1, -1, 25, 0]

我需要这样排序: [0, 1, 25, 85, -1, -1]

尝试使用 sort() 方法但没有运气,因为它不是 ASC 顺序......

逻辑:值代表距离上次订单的天数。-1代表没有顺序。要求按最近订购的顺序订购。


慕妹3242003
浏览 149回答 3
3回答

慕码人8056858

在sort回调中,您收到两个参数(我通常称它们a为 和b)。a如果应该在 之前返回一个负数b,如果无关紧要则返回 0(出于排序目的它们是相同的),如果a应该在 之后返回一个正数b。在您的情况下,由于 -1 最后出现(您说过没有其他负数),您只需要对其进行特殊处理:array.sort((a, b) => {&nbsp; &nbsp; if (a === -1) { // < 0 would also work, since there aren't any others&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }&nbsp; &nbsp; if (b === -1) { // "&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; return a- b;});现场示例:显示代码片段那可以更简洁,当然,我写成上面主要是为了最大程度的清楚。但是例如:array.sort((a, b) => a === -1 ? 1 : b === -1 ? -1 : a - b);就我个人而言,我更喜欢稍微冗长一点。但... :-)

慕村225694

您可以检查是否小于零并将其余的升序排序。var array = [1, 85, -1, -1, 25, 0];array.sort((a, b) => (a < 0) - (b < 0) || a - b);console.log(array);

潇湘沐

您可以sort()像往常一样,然后使用and明确地将-1s 移到末尾。splice()push()let arr = [1, 85, -1, -1, 25, 0];arr.sort((a, b) => a - b);let idx = arr.findIndex(a => a != -1);arr.push(...arr.splice(0, idx));console.log(arr);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答