javascript无法对复杂数组进行排序

我有以下数组要排序。


const input = ["12 - Blue, Red, Orange, Purple", 

"16 - White, Black, Yellow, Blue, Pink",

"14 -  Yellow, Brown, Grey, Maroon, Green",

"20 - Red, Black, Yellow, Peach, Aqua",

"7 - White, Cream, Grey, Green, Magenta" ]

目的是按升序对行进行排序,例如第 7 行,然后是第 12、14、16,最后是第 20。这是我试过但没有用的


const input = [

  "12 - Blue, Red, Orange, Purple",

  "16 - White, Black, Yellow, Blue, Pink",

  "14 -  Yellow, Brown, Grey, Maroon, Green",

  "20 - Red, Black, Yellow, Peach, Aqua",

  "7 - White, Cream, Grey, Green, Magenta"

]


var x = input.sort(function(a, b) {

  return a[0] > b[0] ? 1 : -1;

});


console.log(x)

如何对这样一个复杂的数组进行升序排序?



幕布斯7119047
浏览 102回答 1
1回答

明月笑刀无情

您需要获取整数值并按其增量排序。const    input = ["12 - Blue, Red, Orange, Purple",        "16 - White, Black, Yellow, Blue, Pink",        "14 -  Yellow, Brown, Grey, Maroon, Green",        "20 - Red, Black, Yellow, Peach, Aqua",        "7 - White, Cream, Grey, Green, Magenta"    ];input.sort(function(a, b) {    return parseInt(a, 10) - parseInt(b, 10);});console.log(input);带有分类颜色。const    input = ["12 - Blue, Red, Orange, Purple",        "16 - White, Black, Yellow, Blue, Pink",        "14 -  Yellow, Brown, Grey, Maroon, Green",        "20 - Red, Black, Yellow, Peach, Aqua",        "7 - White, Cream, Grey, Green, Magenta"    ],    sorted = input        .map(s => {            const [number, colors] = s.split(' - ');            return [                number,                colors                    .split(/,\s*/)                    .sort((a, b) => a.localeCompare(b))                    .join(', ')            ].join(' - ');        })       .sort((a, b) => parseInt(a, 10) - parseInt(b, 10));console.log(sorted);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript