我有一个包含许多对象的数组。我正在尝试按升序对数组的前半部分进行排序。数组的后半部分也按升序排列。下面的代码是一个数组示例以及我的方法。我在想是否有一种更聪明的方法来锐化代码并获得相同的结果?有人可以帮忙吗?提前致谢!
var data = [
{id:1, x: 33},
{id:2, x: 22},
{id:3, x: 11},
{id:4, x: 3},
{id:5, x: 2},
{id:6, x: 1}
];
var data1 = [];
for(var i=0; i<3; i++){
data1.push(data[i]);
}
data1.sort (function(a,b) { return a.x - b.x; });
var data2 = [];
for(var i=3; i<6; i++){
data2.push(data[i]);
}
data2.sort (function(a,b) { return a.x - b.x; });
data = data1.concat(data2);
console.log(data);
最佳答案
使用拼接会收紧它:
var data = [
{id:1, x: 33},
{id:2, x: 22},
{id:3, x: 11},
{id:4, x: 3},
{id:5, x: 2},
{id:6, x: 1}
];
// splice out and sort the first half of data
var data1 = data.splice(0,data.length / 2);
data1.sort (function(a,b) { return a.x - b.x; });
// sort the second half
data.sort (function(a,b) { return a.x - b.x; });
data = data1.concat(data);
console.log(data);
关于javascript - 如何使用javascript对数组的一部分进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294175/