【问题标题】:Sorting function for keys in object with closure - Javascript带有闭包的对象中键的排序功能 - Javascript
【发布时间】:2020-01-29 03:26:32
【问题描述】:

我正在为对象中的每个键创建一个单独的函数,如下所示:

对象

let users = [
  { name: "John", age: 20, surname: "Johnson" },
  { name: "Pete", age: 18, surname: "Peterson" },
  { name: "Ann", age: 19, surname: "Hathaway" }
];

简单的排序功能

// Sorting by name (Ann, John, Pete)
users.sort((a, b) => a.name > b.name ? 1 : -1);

// Sorting by age (Pete, Ann, John)
users.sort((a, b) => a.age > b.age ? 1 : -1);

效果很好,但我需要创建一个带闭包的动态函数,它的调用方式如下:

users.sort(byField('name')); 而不是users.sort((a, b) => a.name > b.name ? 1 : -1);

到目前为止我试过这个:

function byField(str) {
  return (a, b) => a.str > b.str ? 1 : -1;
}

console.table(users.sort(byField('name')));
console.table(users.sort(byField('age')));

但它只是返回未排序的对象。

【问题讨论】:

    标签: javascript sorting object closures


    【解决方案1】:

    您需要一个带括号的property accessor 和一个对称地工作并尊重相同值的函数。

    阅读更多关于仅返回部分函数的信息,例如 -11 或仅返回布尔值:Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

    const withKey = key => (a, b) => (a[key] > b[key]) - (a[key] < b[key]);
    
    let users = [{ name: "John", age: 20, surname: "Johnson" }, { name: "Pete", age: 18, surname: "Peterson" }, { name: "Ann", age: 19, surname: "Hathaway" }];
    
    console.log(users.sort(withKey('name')));
    console.log(users.sort(withKey('age')));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 太棒了。谢谢你关于排序功能的那篇文章。这很有趣也很有帮助。
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    相关资源
    最近更新 更多