【问题标题】:Use _sortBy of lodash to sort an array by a different field使用 lodash 的 _sortBy 按不同的字段对数组进行排序
【发布时间】:2018-05-21 15:04:02
【问题描述】:

有一个这样的对象数组:

myArray = [
            {AType: "aaa", Description: "De", …},
            {AType: "bbb", Description: "Hi", …},
            {AType: "ccc", Description: "Un", …},
            {AType: "ddd", Description: "Hw", …}, 
            ];

它按AType排序,但我想按Description排序。

我尝试使用sortBy from lodash

import _sortBy from 'lodash/sortBy';

mySortedArray = _sortBy(myArray, s => s.Description);

它没有达到我的预期,结果看起来像:[Array(4), Array(3), {…}, {…}]

任何想法如何按该字段对其进行排序但也不修改数组内的任何其他内容?

【问题讨论】:

  • 它工作正常。也许导入是错误的......
  • (追上之前的问题)AngularJS orderBy 有一个有效的解决方案,这是一个example in Plunker
  • @NinaScholz 你是对的,导入不正确

标签: javascript arrays sorting lodash


【解决方案1】:

不确定到底是什么问题。同样对于像这样的简单排序,您不需要箭头函数,只需要属性名称。

myArray = [
    {AType: "aaa", Description: "De"},
    {AType: "bbb", Description: "Hi"},
    {AType: "ccc", Description: "Un"},
    {AType: "ddd", Description: "Hw"}
];

mySortedArray = _.sortBy(myArray, 'Description');

console.log(mySortedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2021-11-09
    • 2017-09-08
    • 2015-05-10
    • 2018-05-13
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多