// custom sort function to be passed as param/callback to the Array's sort methodfunction myCustomSort(a, b) {return (a.toLowerCase() > b.toLowerCase()) ? 1 : -1;}
// Actual method to be called by entity that needs sorting featurefunction sortStrings() {var op = Array.prototype.sort.call(arguments, myCustomSort);}
// Testing the implementationvar sortedArray = sortStrings("Burger", "Mayo1", "Pizza", "boxes", "Apples", "Mayo");console.log(sortedArray); //["Apples", "boxes", "Burger", "Mayo", "Mayo1", "Pizza"]
obj.sort((a, b) => a.lname.localeCompare(b.lname))
所以我们需要检查如下所示的假值
let obj=[{name:'john',lname:'doe',address:'Alaska'},{name:'tom',lname:'hopes',address:'California'},{name:'harry',address:'Texas'}]let field='lname';console.log(obj.sort((a, b) => (a[field] || "").toString().localeCompare((b[field] || "").toString())));
或
我们可以使用lodash,非常简单。它将检测返回值,即数字或字符串,并相应地进行排序。
import sortBy from 'lodash/sortBy';sortBy(obj,'name')
const collator = new Intl.Collator('zh-CN'); // Chinese Simplified for example
function sortAsc(a, b) {if (typeof a === 'string' && typeof b === 'string') {return collator.compare(b, a)}
return b - a;}
function sortDesc(a, b) {if (typeof a === 'string' && typeof b === 'string') {return collator.compare(a, b);}
return a - b;}