Reputation: 3938
I have a JavaScript object:
var javascriptObj = response[Object.keys(response)[Object.keys(response).length - 1]]
which looks like this:
[["1", 121], ["10", 58], ["2", 69], ["3", 246], ["4", 3], ["5", 446], ["6", 124], ["7", 396], ["8", 190], ["9", 46]]
Is there a way to convert the values ("1","2","3") into integer and then sort the object based on this number?
EDITED
The values don't always stay the same. Some times it is from 1 to 5 or 8-13. And also it can be that there are missing values in between.
Upvotes: 1
Views: 3528
Reputation: 5122
Try something like this ...
myArray.sort(function(a, b) {return parseInt(a[0], 10) - parseInt(b[0], 10)});
UPDATE: Changed a[1] and b[1] to a[0] and b[0].
Upvotes: 2
Reputation: 66590
Try this:
var javascriptObj = [["1", 121], ["10", 58], ["2", 69], ["3", 246], ["4", 3], ["5", 446], ["6", 124], ["7", 396], ["8", 190], ["9", 46]];
var output = javascriptObj.map(function(array) {
return [+array[0], array[1]];
}).sort(function(a, b) {
return a[0]-b[0];
});
document.getElementsByTagName('div')[0].innerHTML = JSON.stringify(output);
<div></div>
Upvotes: 3