2016-03-29 4 views
0

У меня есть массив, содержащий много объектов. Я пытаюсь сортировать первую половину массива с возрастающим порядком. А вторая половина массива с восходящим порядком тоже. Ниже приведен пример массива и мой способ сделать это. Я думаю, есть ли более умный способ обострить код и получить тот же результат? Может ли кто-нибудь помочь? Заранее спасибо!Как отсортировать часть массива с помощью javascript?

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); 
+2

http://codereview.stackexchange.com –

+0

вы можете сказать нам, как вы хотите заказать? по id или x? – JordanHendrix

+1

FYI, вы можете немного сократить его, избавившись от циклов 'for' и вместо этого сделайте следующее:' var data1 = data.splice (data.length/2); var data2 = data' –

ответ

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); 
+0

Почему этот 'data.splice (1, data.length/2)' должен работать в таком случае? 'console.log (data)' дает следующий порядок атрибута 'x':' 3, 11, 22, 1, 2, 33 ' – RomanPerekhrest

+0

@nnnnnn yes, it should. Закрепление. – xrgb

0

Вы можете разрезать массив с Array#slice() и CONCAT с 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>');

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