Click here to Skip to main content
15,886,791 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a JSON array and it looks like that:
```js
JSON
{
    _time: 30,
    _customData: {
      //some more stuff here but its not important in this case
    },
  },
  {
    _time: 5,
    _customData: {
      //some more stuff here but its not important in this case
    },
  },
  {
    _time: 20,
    _customData: {
      //some more stuff here but its not important in this case
    },
  }
```

Now Im trying to sort it so it would be like:
```
JSON
{
    _time: 5,
    _customData: {
      //some more stuff here but its not important in this case
    },
  },
  {
    _time: 20,
    _customData: {
      //some more stuff here but its not important in this case
    },
  },
  {
    _time: 30,
    _customData: {
      //some more stuff here but its not important in this case
    },
  }
```

For the last hour Ive been trying to sort it and right now I have nothing.
I would appreciate the help a lot!

What I have tried:

I tried to use a for loop and find the biggest _time value but that didn't work
Posted
Updated 8-Mar-22 6:32am
v2
Comments
PIEBALDconsult 8-Mar-22 12:33pm    
For what purpose?

JSON is a data transfer format, it is not a data processor in any way. All it does is describe data in a language- and framework- independent way so that it can be produced by any system and read correctly on any other.

As such, it's not sortable, or even really searchable in it's native JSON - it only becomes sortable once it has been read into your specific language and framework. Until then, it is just a string! This process is called parsing

So start there: JSON.parse()[^] and once you have your data as an array of Javascript objects, sorting (and all other processing) becomes simple!
 
Share this answer
 
v2
Comments
TzurS11 6-Mar-22 14:03pm    
I already have it as json forgot to say that sorry
OriginalGriff 6-Mar-22 14:32pm    
Then just sort that ... what is the problem?
TzurS11 6-Mar-22 14:44pm    
got it to work thanks anyways!
OriginalGriff 6-Mar-22 15:48pm    
You're welcome!
Solution:
json.sort(function (a, b) {
  return a._time - b._time;
});
 
Share this answer
 
after ES6:

json.sort((a, b) => a._time) - b._time));


Taken from here:
Sorting an array of objects by property values[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900