1

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.

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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].

4 Comments

it should be a[0] and b[0]
Shouldn't it be a[0] and b[0]?
Thanks for the answer. 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.
@dkar: I think you should update your question with whatever you have commented above so that other people can read them before solving.

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.