简体   繁体   English

按嵌套对象值对数组进行排序

[英]Sorting an array by nested object value

I have an array with a structure similar to this:我有一个结构与此类似的数组:

links = [
{
orig:{ src:"A", target:"B"},
source:{},
target:{}
},
{
orig:{ src:"B", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"A"},
source:{},
target:{}
},
{
orig:{ src:"A", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"B"},
source:{},
target:{}
}
]

I need to sort this array on nested values "src" and "target" that are in the "orig" object.我需要根据“orig”对象中的嵌套值“src”和“target”对该数组进行排序。 It should be sorted alphabetically on "src", and if several "src" with same value then it uses "target" in order to see which one is to be placed before the other.它应该在“src”上按字母顺序排序,如果多个“src”具有相同的值,则它使用“target”来查看将哪个放在另一个之前。

The desired sorted result should be:所需的排序结果应该是:

links = [
{
orig:{ src:"A", target:"B"},
source:{},
target:{}
},
{
orig:{ src:"A", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"B", target:"C"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"A"},
source:{},
target:{}
},
{
orig:{ src:"C", target:"B"},
source:{},
target:{}
}
]

The array I need to sort has over 8 thousand lines.我需要排序的数组有超过 8000 行。 What would be an efficient way to achieve this?什么是实现这一目标的有效方法? I have figured out a "dirty" way to do it with several nested loops, but with 8000 lines in the array it took very long to process.我已经找到了一种“肮脏”的方法来使用几个嵌套循环来完成它,但是数组中有 8000 行,它需要很长时间才能处理。 So it is not a viable solution.所以这不是一个可行的解决方案。

Here's a simple sort on orig.src then on orig.target:这是对 orig.src 然后在 orig.target 上的简单排序:

 const links = [ { orig: { src: "A", target: "B" }, source: {}, target: {}, }, { orig: { src: "B", target: "C" }, source: {}, target: {}, }, { orig: { src: "C", target: "A" }, source: {}, target: {}, }, { orig: { src: "A", target: "C" }, source: {}, target: {}, }, { orig: { src: "C", target: "B" }, source: {}, target: {}, }, ]; links.sort(function (a, b) { return ( a.orig.src.localeCompare(b.orig.src) || a.orig.target.localeCompare(b.orig.target) ); }); console.log(links);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM