1

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.

1
  • use data['nested-name'] Commented Aug 16, 2017 at 0:21

2 Answers 2

4

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" ]) )
Sign up to request clarification or add additional context in comments.

3 Comments

How can i ignore case sensitivity?
@NewBee add toLowerCase()
=> a.data["nested-name"].toLowerCase() > b.data[ "nested-name" ].toLowerCase() - or use => a.data["nested-name"].localeCompare(b.data["nested-name"])
1

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);

1 Comment

How can i ignore case sensitivity?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.