我有一个类似的数组:
['honda accord', '1986 honda accord', '1990 honda accord', '2000 honda accord', '2011 honda accord', '2016 honda accord'].
我需要在javascript中对此进行排序,以便结果为:
['honda accord', '2016 honda accord', '2011 honda accord', '2000 honda accord', '1990 honda accord', '1986 honda accord'].
我该怎么做。
array.sort()
不起作用。 我知道我需要发送一个函数来排序。
由于 布赖恩
答案 0 :(得分:2)
您可以使用split
并检查字符串的第一项
var arr = ['honda accord', '1986 honda accord', '1990 honda accord', '2000 honda accord', '2011 honda accord', '2016 honda accord'];
arr.sort((a, b) => b.split(' ')[0] - a.split(' ')[0])
document.write(JSON.stringify(arr));
答案 1 :(得分:1)
工作小提琴: https://jsfiddle.net/7nu7bp3g/
var arr = [
'honda accord',
'1986 honda accord',
'1990 honda accord',
'2000 honda accord',
'2011 honda accord',
'2016 honda accord'
];
var sortArr = arr.sort(function(a, b) {
return b.split(' ')[0] - a.split(' ')[0];
});
console.log(sortArr);
我希望它能奏效。
答案 2 :(得分:0)
它不是很优雅(或高效)但它有效。基本上它使用正则表达式从每辆车中提取年份然后进行比较。
// the regular expression to extract the year and car
var regEx = /((\d+)\s)*(.*)/;
var list = ['honda accord', '1986 honda accord', '1990 honda accord', '2000 honda accord', '2011 honda accord', '2016 honda accord'];
// custom sort function
list.sort(function(a, b)
{
// get the car details
var aR = regEx.exec(a);
var bR = regEx.exec(b);
var aCar = aR[3];
var bCar = bR[3];
var aYear = aR[2];
var bYear = bR[2];
// compare the strings
if(aCar < bCar) return -1;
else if(aCar > bCar) return 1;
// we'll only get this far if both strings are the same
// if there was no year provided then it should be first
else if(!aYear) return -1;
else if(!bYear) return 1;
// at this point the car types are the same, and both have an year so compare the year
else if(aYear < bYear) return 1;
else if(aYear > bYear) return -1;
return 0;
})
通过预处理列表以在所有项目上运行正则表达式,可以提高效率。
答案 3 :(得分:0)
如果没有给出年份,则替换为
var array = ['honda accord', '1986 honda accord', '1990 honda accord', '2000 honda accord', '2011 honda accord', '2016 honda accord'];
array.sort((a, b) => b.replace(/^\D*$/g, '9999 $1').localeCompare(a.replace(/^\D*$/g, '9999 $1')));
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');