简体   繁体   English

根据每个数组内的值对对象内的数组进行排序

[英]Sort arrays inside object based on value inside each array

I have a JavaScript object: 我有一个JavaScript对象:

 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? 有没有一种方法可以将值(“ 1”,“ 2”,“ 3”)转换为整数,然后根据该数字对对象进行排序?

EDITED 已编辑

The values don't always stay the same. 值并不总是保持不变。 Some times it is from 1 to 5 or 8-13. 有时是1到5或8-13。 And also it can be that there are missing values in between. 也可能是两者之间缺少值。

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> 

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]. 更新 :将a [1]和b [1]更改为a [0]和b [0]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM