Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中按特定值对数组排序_Javascript_Sorting_Reverse - Fatal编程技术网

javascript中按特定值对数组排序

javascript中按特定值对数组排序,javascript,sorting,reverse,Javascript,Sorting,Reverse,如果我有如下数组: var myArray = [] for(i = 0; i < 10; i++) { myArray.unshift({ myString: 'string'+ i +'', myValue: i; }); } 但是,这不起作用。您的意思是希望按myValue进行排序 myArray.sort(function a, b) { return a.myValue - b.myValue; }); 如果只想对一个对象属性进行排序(其余属性保持不变

如果我有如下数组:

var myArray = []

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

但是,这不起作用。

您的意思是希望按myValue进行排序

myArray.sort(function a, b) { 

  return a.myValue - b.myValue;

});

如果只想对一个对象属性进行排序(其余属性保持不变),则必须复制数组中每个项的特定属性,对其进行排序,然后将属性复制回:

// 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; });

你能分享样本的输入和输出吗?像这样吗
myArray.sort(函数a,b){return a.myValue-b.myValue})
他只想对数组中对象的一个特定属性进行排序,其他属性保持不变-他不想按某个属性对整个数组进行排序。
// 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; });