我有一个包含许多对象的数组。我试图按升序排序数组的前半部分。并且数组的后半部分也按升序排列。下面的代码是一个数组示例和我的方法。我在想是否有更聪明的方法来锐化代码并获得相同的结果?有人可以帮忙吗?提前谢谢!
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);
答案 0 :(得分:3)
使用拼接将其收紧:
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);
答案 1 :(得分:1)
/**
* This method allows you to split array in two peaces
* @param Array array - the array which you want to split
* @returns array
*/
function sort2Array(array) {
var results = [],
length = Math.ceil(array.length / 2),
iterations = array.length / length;
for (var i = 0; i < iterations; i++) {
var peace = array.slice(i * length, (i + 1) * length);
results.push(peace.sort(function(a, b) { return a.x - b.x; }));
}
return results[0].concat(results[1]);
}
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 }
]
sort2Array(data);
答案 2 :(得分:0)
您可以使用Array#slice()
对数组进行切片,并使用Array#concat()
进行联接。
function sortX(a, b) {
return a.x - b.x;
}
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 }],
first = data.slice(0, data.length / 2 | 0).sort(sortX),
second = data.slice(data.length / 2 | 0, data.length).sort(sortX);
data = first.concat(second);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
答案 3 :(得分:0)
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 sort_fn = function(a,b) { return a.x - b.x; };
function half_sort(p) {
var m = p.length/2;
return Array.prototype.concat(
p.slice(0, m).sort(sort_fn),
p.slice(m).sort(sort_fn) )
}
var result = half_sort(data)
答案 4 :(得分:0)
使用ES6
let 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}
];
const up = data.slice(0,data.length/2).sort((prev,next) => prev.x - next.x);
const low = data.slice(data.length/2,data.length).sort((prev,next) => next.x - prev.x);
data = up.concat(low)