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), {});
}
-
2Possible duplicate of Sort array of objects by string property value in JavaScriptt.niese– t.niese2018年01月22日 05:38:51 +00:00Commented Jan 22, 2018 at 5:38
-
Or this one: Sorting an array of JavaScript objectst.niese– t.niese2018年01月22日 05:41:42 +00:00Commented Jan 22, 2018 at 5:41
-
That was it...apologies. Your first link. Didn't see it in my search. Thank you.Cybernetic– Cybernetic2018年01月22日 05:44:51 +00:00Commented Jan 22, 2018 at 5:44
5 Answers 5
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);
Comments
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);
1 Comment
parseFloat?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');
Comments
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);
Comments
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;
});