如果我有Javascript对象:
var myObject = {
dataset : [],
};
myObject.dataset.push({data : [1,5,4,6]});
myObject.dataset.push({data : [2,4,7,4]});
myObject.dataset.push({data : [12,53,4,45]});
然后我想根据特定的数据排序 ALL datasets.data BUT 。 fx第一个。 myObject.dataset [0]。数据
预期结果:
0 : ({data : [1,4,5,6]}); // sorted list
1 : ({data : [2,7,4,4]}); // others match the changes.
2 : ({data : [12,4,53,45]});
类似的东西:
for(i = 0; i < myObject.dataset.length; i++) {
myObject.dataset[i].data.sort( BASED ON myObject.dataset[0].data )
}
答案 0 :(得分:1)
这应该这样做。我添加了评论以显示正在发生的事情......
var something = {
dataset: [],
};
something.dataset.unshift({data : [1,5,4,6]});
something.dataset.unshift({data : [1,5,8,6]});
something.dataset.unshift({data : [2,4,7,4]});
something.dataset.unshift({data : [12,53,4,45]});
something.dataset.unshift({data : [11,52,41,16]});
something.dataset.unshift({data : [1,53,43,64]});
something.dataset.unshift({data : [1,5,8,6,3]});
//This function is used when sorting two cells in an array
//See the Array.prototype.sort method on MDN for more info
//Returning -1 keeps (a,b)->(a,b), returning 1 swaps (a,b)->(b,a)
var asc = function(a,b) {return a<b?-1:1; };
//Sort the whole dataset, based on the values of each array
something.dataset.sort(function(a,b) {
//The arguments a and b are cell objects in something.dataset
//Sort each of the data arrays for the objects
a.data.sort(asc);
b.data.sort(asc);
//Tricky part is if a.data[0] and b.data[0] are equal
//Find the first cell of both arrays that are not equal
var i=0;
var al = a.data.length;
var bl = b.data.length
var l=Math.min(al,bl);
while(i<l && a.data[i]===b.data[i]) i++;
//All the values for the shortest of both arrays are equal! Sort by the length of the arrays instead
if(i>=l) return asc(al,bl);
//We found a non-equal cell in both arrays, sort by it!
return asc(a.data[i],b.data[i]);
});
console.log(JSON.stringify(something));
答案 1 :(得分:1)
此解决方案将数据重新组合成一个新的数组数组,对它们进行排序并将数据移回:</ p>
var regrouped=[];
for (var i=0; i<myObject.dataset[0].data.length; i++) {
regrouped.push([]);
}
for (var j=0; j<myObject.dataset[0].data.length; j++) {
for (i=0; i<myObject.dataset.length; i++) {
regrouped[j][i]=myObject.dataset[i].data[j];
}
}
regrouped.sort(function(a,b){return a[0]-b[0];});
for (i=0; i<myObject.dataset.length; i++) {
for (j=0; j<myObject.dataset[0].data.length; j++) {
myObject.dataset[i].data[j]=regrouped[j][i];
}
}
答案 2 :(得分:0)
如果您愿意使用lodash或下划线js库。您可以使用此lodash函数来实现您想要的非常简单和优雅。
var something = {
dataset: [],
};
something.dataset.unshift({data : [1,5,4,6]});
something.dataset.unshift({data : [2,4,7,4]});
something.dataset.unshift({data : [12,53,4,45]});
something.dataset.unshift({data : [11,52,41,16]});
something.dataset.unshift({data : [1,53,43,64]});
_.forEach(something.dataset, function(data){
console.log(data.data);
data.data = _.sortBy(data.data);
});
console.log(something);