有什么方法可以扩展 javascript 的 array.sort() 方法以接受另一个参数? [英] Any way to extend javascript's array.sort() method to accept another parameter?
问题描述
我正在尝试对一组对象进行排序.我不想为每个属性编写自定义排序方法.
I'm trying to sort an array of objects. I'd prefer not to write a custom sort method for each attribute.
无论如何我可以扩展内置的 array.sort()
方法来接受一个额外的参数,描述要排序的属性?例如,
Is there anyway I could extend the built-in array.sort()
method to accept an extra parameter, describing the attribute to sort on? E.g.,
array.sort(function(a, b, attr) { return a.attr - b.attr; }, 'name');
推荐答案
编写一个接受属性名称的函数生成器:
Write a function generator that accepts a property name:
function propComparator(prop) {
return function(a, b) {
return a[prop] - b[prop];
}
}
arr.sort(propComparator('name'));
您还可以直接保存分拣机或作为参数保存供以后使用:
You can also save the sorters for later use, directly, or as parameters:
var compareNames = propComparator('name');
var compareFoos = propComparator('foo');
...
arr.sort(compareNames);
takesComparator(compareFoos);
针对 ES6 进行了更新,使其适用于不同的类型.
Updated for ES6, and make it so it actually works with different types.
请注意,sort
进行就地排序,这可能会也可能不理想.
Note that sort
sorts in-place, which may or may not be desirable.
const arr = [
{ name: 'John', age: 92 },
{ name: 'Dave', age: 42 },
{ name: 'Justin', age: 3 }
]
const propComparator = (propName) =>
(a, b) => a[propName] == b[propName] ? 0 : a[propName] < b[propName] ? -1 : 1
arr.sort(propComparator('name'))
console.log("By name", arr)
arr.sort(propComparator('age'))
console.log("By age", arr)
这篇关于有什么方法可以扩展 javascript 的 array.sort() 方法以接受另一个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!