1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
您需要獲取整數(shù)值并按其增量排序。
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);
添加回答
舉報(bào)