gpt4 book ai didi

javascript - 如何按两个属性对json数据进行排序

转载 作者:行者123 更新时间:2023-12-03 08:13:06 25 4
gpt4 key购买 nike

http://jsfiddle.net/dy8w8r7d/

如何按两个属性对 JSON 数据进行排序?下面的函数仅按Episode排序..

目标:按Episode升序排列,然后按Sequence升序排列

var data = [ { ArticleId: 2, Episode: 1, Type: 0, Sequence: 0 },
{ ArticleId: 1, Episode: 1, Type: 0, Sequence: 1 },
{ ArticleId: 3, Episode: 2, Type: 0, Sequence: 0 },
{ ArticleId: 4, Episode: 2, Type: 0, Sequence: 1 } ];

var data = [ { ArticleId: 2, Episode: 1, Type: 0, Sequence: 1 },
{ ArticleId: 1, Episode: 2, Type: 0, Sequence: 0 },
{ ArticleId: 3, Episode: 1, Type: 0, Sequence: 0 },
{ ArticleId: 4, Episode: 2, Type: 0, Sequence: 1 } ];


function compareEpisodeSequence(a,b) {
if (a.Sequence < b.Sequence)
return -1;
if (a.Sequence > b.Sequence)
return 1;
return 0;
}
data.sort(compareEpisodeSequence);

console.log(data);

最佳答案

这应该做你想做的事:

function compareEpisodeSequence(a,b) {
if (a.Episode < b.Episode) return -1;
if (a.Episode > b.Episode) return 1;
if (a.Sequence < b.Sequence) return -1;
if (a.Sequence > b.Sequence) return 1;
return 0;
}

如果剧集相等,则继续比较序列

关于javascript - 如何按两个属性对json数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com