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