Reputation: 13354
I have an object in JS structured as follows:
[{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}]
I need to sort by one of the keys in each element (sort by x). The result would look like this:
[{
"x": 2.18,
"y": 0.458
},
{
"x": 2.31,
"y": 0.538
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 7.07,
"y": 0.469
}]
The following approach doesn't work with the above structure:
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
Nor does the following:
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Upvotes: 1
Views: 87
Reputation: 1639
What you have do here is implement a custom sort method for comparison between the elements in your array.
Try this out.
const array = [{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}];
array.sort((obj1, obj2) => {
return obj1.x - obj2.x;
});
Upvotes: 0
Reputation: 8950
You can use Javascript builtin sort() method to do that.
var myList = [{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}];
var sortedList = myList.sort(function(a, b){
return a.x - b.x;
});
console.log(sortedList);
Upvotes: 0
Reputation: 22574
Implement a custom sort method.
var arr = [{ "x": 2.31, "y": 0.538 }, { "x": 7.07, "y": 0.469 }, { "x": 6.02, "y": 0.469 }, { "x": 2.18, "y": 0.458 }]
arr.sort((a,b) => a.x - b.x)
console.log(arr);
Upvotes: 1
Reputation: 1410
You can use lodash. https://lodash.com/docs/4.17.4#sortBy
lodash is a modern JavaScript utility library delivering modularity, performance & extras.
Demo: http://jsfiddle.net/e2ccmbhh
let arr = [{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}]
let sortedArr = _.sortBy(arr, 'x');
Upvotes: 0
Reputation: 2087
Yes, you can sort the key value of the object by comparing the key's value using parseFloat.
var coordinates=[{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}]
var sortedKey=coordinates.sort(function(a, b) {
return parseFloat(a.x) - parseFloat(b.x);
});
console.log(sortedKey);
Upvotes: 0