简体   繁体   English

在javascript中按特定值对数组进行排序

[英]sorting array by certain value in javascript

if i have an array like:如果我有一个像这样的数组:

var myArray = []

for(i = 0; i < 10; i++) {
 myArray.unshift({
  myString: 'string'+ i +'',
  myValue: i;
 });
}

and want to sort it by the 'myValue' values.并希望按“myValue”值对其进行排序。 like喜欢

myArray.myValue.sort (function(a, b){return a-b});

however, this is not working.然而,这是行不通的。

You mean you wish to sort by myValue ?你的意思是你想按myValue排序?

myArray.sort(function a, b) { 

  return a.myValue - b.myValue;

});

If you want to sort only one object property (while leaving the rest untouched), what you will have to do is make a copy of that specific property of each item in the array, sort that, and then copy the properties back over:如果您只想对一个对象属性进行排序(而其余部分保持不变),您需要做的是复制数组中每个项目的特定属性,对其进行排序,然后将属性复制回来:

// make a copy of the myValues into a new array containing just those
var myValueArray = myArray.map(function(item) { return item.myValue; });
// sort just the myValues in the copy 
myValueArray.sort();
// copy the sorted myValues back
myValueArray.forEach(function(item, index){ myArray[index].myValue = item; });

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

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