【问题标题】:Sorting Json data based on a field根据字段对 Json 数据进行排序
【发布时间】:2017-04-13 17:14:07
【问题描述】:

我有一个 Json 数据需要在显示之前对其进行排序。我的Json如下。我需要根据 ColumnLocation 对它们进行排序。

[{
  "Name": "PieChart",
  "Id": "1",
  "ColumnLocation": "0",
  "RowLocation": "0"
}, {
  "Name": "Calendar",
  "Id": "2",
  "ColumnLocation": "1",
  "RowLocation": "0"
}, {
  "Name": "FavouriteFilter",
  "Id": "3",
  "ColumnLocation": "2",
  "RowLocation": "0"
}, {
  "Name": "FilterResults",
  "Id": "4",
  "ColumnLocation": "0",
  "RowLocation": "1"
}, {
  "Name": "Watched",
  "Id": "5",
  "ColumnLocation": "1",
  "RowLocation": "1"
}]

即排序后的数组应具有以下方式的项目

col : 0, row 0
col : 0, row 1
col : 1, row 0
col : 1, row 1

【问题讨论】:

  • 看不到任何 json,只有“遵循时尚的项目”。但是,方法是,从 JSON 转换为 JS 对象/数组/无论它们是什么,运行您的排序(取决于您的 JSON 变成什么),然后就可以了。 JSON 只是一个字符串,要应用典型的排序算法,您必须转换它(JSON.parse)。
  • @TimConsolazio 抱歉刚刚添加了 Json。
  • 把答案贴在下面。

标签: javascript ecmascript-6 underscore.js lodash


【解决方案1】:

不需要 lodash/下划线。您可以使用Array.prototype.sort: 由于您的值是字符串,因此您必须先将它们解析为数字,然后进行比较:

let a = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

let sorted = a.sort((a, b) => parseInt(a.ColumnLocation) - parseInt(b.ColumnLocation));

console.log(sorted);

【讨论】:

  • 确实,这是设计得更好的比较函数(减法返回数字数据类型)(+1)。
【解决方案2】:

短而甜。

let arr = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

arr.sort ( ( a, b ) => { return parseInt ( a.ColumnLocation ) > parseInt ( b.ColumnLocation ) } );

console.log ( arr );

请注意,如果您不转换为数字,则排序不会是您所期望的。

【讨论】:

  • 这种排序可能不稳定:您提供给sort 的比较函数应该返回一个可以是负数、零或正数的数字,但此函数返回一个布尔值,因此绝不会是负值。
  • 原始值没有问题,因为它们在相等时无法区分。但总的来说,最好像接受的答案那样做减法,因为它会导致稳定的排序(“稳定”只有在你能区分等于排序条件的值时才有意义,但会有其他属性用于制作区别)。这是一个最佳实践问题。
  • 所以在这种用法中,排序没有问题。谢谢。
  • 啊,我看到SO集团又找到了我。嗯,享受你的 DV。
【解决方案3】:

为什么不使用 _.sortBy (http://underscorejs.org/#sortBy)?

var mysortedarray = _.sortBy(myarray, 'ColumnLocation');

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 2016-11-17
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多