有什么方法可以扩展javascript的array.sort()方法来接受另一个参数? [英] Any way to extend javascript's array.sort() method to accept another parameter?
问题描述
我正在尝试对一组对象进行排序。我不想为每个属性编写自定义排序方法。
无论如何我可以扩展内置的 array.sort( )
接受额外参数的方法,描述要排序的属性?例如,
array.sort(function(a,b,attr){return a.attr - b.attr;}, '名称');
编写一个接受属性名称的函数生成器: / p>
function propComparator(prop){
return function(a,b){
return a [prop] - b [prop];
}
}
arr.sort(propComparator('name'));
您也可以保存分拣机以供以后使用,直接或作为参数:
var compareNames = propComparator('name');
var compareFoos = propComparator('foo');
...
arr.sort(compareNames);
takeComparator(compareFoos);
针对ES6进行了更新,并使其实际上适用于不同类型。
请注意 sort
就地排序,这可能是也可能不合适。
const arr = [{name:'John',年龄:92},{name:'Dave',年龄:42} ,{name:'Justin',年龄:3}] const propComparator =(propName)=> (a,b)=> a [propName] == b [propName]? 0:[propName]< b [propName]? -1:1arr.sort(propComparator('name'))console.log(By name,arr)arr.sort(propComparator('age'))console.log(by age,arr)
I'm trying to sort an array of objects. I'd prefer not to write a custom sort method for each attribute.
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);
Updated for ES6, and make it so it actually works with different types.
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屋!