[英]Javascript custom sort, group certain items at bottom and sort within
In javascript, I have an array of items like so:在javascript中,我有一个像这样的项目数组:
[
'title',
'firstname',
'company',
'[m]usr_phone'
'[m]usr_city'
]
I would like to sort this using a custom array sort function so that all the non [m] items are sorted at the top, and all the [m] items are sorted and pushed to the bottom (after all the non [m] items)我想使用自定义数组排序函数对其进行排序,以便所有非 [m] 项排序在顶部,所有 [m] 项都排序并推到底部(在所有非 [m] 项之后)
To achieve this I tried a sort function like this:为了实现这一点,我尝试了这样的排序功能:
function(a, b) {
if (!a.indexOf('[m]') && b.indexOf('[m]') === 0
|| a.indexOf('[m]') && b.indexOf('[m]')) {
return -1;
}
if (a.indexOf('[m]') === 0 && !b.indexOf('[m]')) {
return 1;
}
return 0;
}
But couldn't get it to work properly.但无法让它正常工作。 I would like the output to be:
我希望输出是:
[
'company',
'firstname',
'title',
'[m]usr_city'
'[m]usr_phone'
]
Thanks for your help!谢谢你的帮助!
You could check the prefix and sort later by String#localeCompare
.您可以检查前缀并稍后按
String#localeCompare
排序。
var array = ['title', 'firstname', 'company', '[m]usr_phone', '[m]usr_city']; array.sort(function (a, b) { return (a.slice(0, 3) === '[m]') - (b.slice(0, 3) === '[m]') || a.localeCompare(b); }); console.log(array);
You want to compare items in the same “class” (ie either starting with [m]
or not) the same way, so use a.startsWith("[m]") == b.startsWith("[m]")
to do this, and then use String#localeCompare
.您想以相同的方式比较同一“类”中的项目(即以
[m]
开头或不以[m]
开头),因此使用a.startsWith("[m]") == b.startsWith("[m]")
要做到这一点,然后使用String#localeCompare
。
console.log([ "company", "firstname", "title", "[m]usr_phone", "[m]usr_city" ].sort((a, b) => { if (a.startsWith("[m]") == b.startsWith("[m]")) { return a.localeCompare(b); } else { return (a.startsWith("[m]") ? 1 : -1); } }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.