NewBee
NewBee

Reputation: 839

Sorting JSONarray by nested property

I am trying to sort array of JSON values, but the property to sort is nested within the JSON object. For this example the sort is to be done using data.nested-name.

I tried using https://stackoverflow.com/a/8175221/2053159 but without any success.

[
{
name: 'a75',
data: {nested-name:"zz\, Hello// There="}},
{
name: 'z32',
data: {nested-name:"aa\, Hello// There="}},
];

expected output ->

[
{
name: 'a75',
data: {nested-name:"aa\, Hello There="}},
{
name: 'z32',
data: {nested-name:"zz\, Hello There="}},
];

Nested name do contain lot of back and forward slashes and other special characters. I don't use external libraries, please provide solutions using native JavaScript.

Upvotes: 1

Views: 819

Answers (2)

vox
vox

Reputation: 837

Assuming arr is your array, you can sort like so:

arr.sort( ( a, b ) => a.data[ "nested-name" ] > b.data[ "nested-name" ] )

For higher string comparison accuracy you can use localeCompare

arr.sort( ( a, b ) => a.data[ "nested-name" ].localeCompare(b.data[ "nested-name" ]) )

Upvotes: 4

Alex Kudryashev
Alex Kudryashev

Reputation: 9470

array.sort function takes an optional argument function(a,b) which must return -1, 0, or 1 depending on comparison.
Your data definition contains an error nested-name:"zz\, Hello// There=". If you use - then you must quote the name.
Working sample is here.

var arr=[
{
name: 'a75',
data: {'nested-name':"zz\, Hello// There="}},
{
name: 'z32',
data: {'nested-name':"aa\, Hello// There="}},
];

var result=arr.sort(function(a,b){
  return a.data["nested-name"] > b.data["nested-name"];
  });
  console.log(result);

Upvotes: 1

Related Questions