1 回答
TA贡献1828条经验 获得超4个赞
您需要获取整数值并按其增量排序。
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);
添加回答
举报