2017-02-22 24 views
0

Я получаю массив так:JavaScript - Как отсортировать массив массива по числовым строкам?

[ 
    [{"name":"one","team":"------","checked":false,"position":"-"}, 
    {"name":"two","team":"------","checked":false,"position":"1"}], 
    [{"name":"three","team":"------","checked":false,"position":"3"}, 
    {"name":"four","team":"------","checked":false,"position":"7"}] 
] 

Я хочу, чтобы конечный результат будет так:

[ 
    [{"name":"two","team":"------","checked":false,"position":"1"}, 
    {"name":"four","team":"------","checked":false,"position":"7"}], 
    [{"name":"three","team":"------","checked":false,"position":"3"}, 
    {"name":"one","team":"------","checked":false,"position":"-"}] 
] 

Это означает, что массив отсортирован по наибольшему значению положения и наименьшего значения позиции в первом вспомогательном массиве, затем второе наибольшее значение местоположения и второе значение наименьшей позиции во втором подматрице. Если есть позиция «-», она остается после номеров строк.

До сих пор я попытался это с lodash:

var mergedArray = vm.roundOf4[0].concat(vm.roundOf4[1]); 
var count = _.countBy(mergedArray, {position: '-'}); 

var ascArray = _.cloneDeep(mergedArray); 
var descArray = _.cloneDeep(mergedArray); 

_.sortByOrder(ascArray, 'position', 'asc'); 
_.sortByOrder(descArray, 'position', 'desc'); 

_.times(count.true, ascArray.push(ascArray.shift())); 

vm.roundOf4.some(function (array, i) { 
    array.some(function (object, j) { 

     if (j === 0) { 
      vm.roundOf4[i][j] = ascArray[i]; 

     } else if (j === 1) { 
      vm.roundOf4[i][j] = descArray[i]; 
     } 

    }); 
}); 

Но восходящая сортировать по функции не правильно сортировки значение позиции, так что это дает случайную сортировку. Я не знаю, является ли это потому, что позиция является строковым значением.

Должен ли я использовать цифры вместо этого?

+2

'1' и' -' находились в одной и той же подрешетке, но в желаемом выходе они разделены. Какова логика этого? –

+0

Нет логики, только «-» еще не установлен. Это может быть другое число, но поскольку оно еще не установлено, оно остается в конце, то же самое применимо к любому объекту. – forkfork

+1

Не говоря о '-', я говорю о том, как' 1' и '-' были отделены друг от друга после сортировки! (** до: ** они находились в одном и том же поддиапазоне, ** после: ** каждый пошел в другую подматрицу)! То же самое для '7' и' 3'! –

ответ

0

// get an array of object an return the min index or the max index depending on the parameter max (true => max index, false => min index) 
 
function minMax(arr, max) { 
 
    var index = 0;            // assuming the index 0 is the min or max 
 
    for (var i = 1; i < arr.length; i++) {      // for each other object in the array 
 
    if(arr[index].position == '-')       // if the position of the object at index index is '-' then assume the index is this i (before starting the comparison, find an item which have a number for its position property) 
 
     index = i; 
 
    else if ((arr[i].position > arr[index].position) == max) // now that the object at index index has a valid position property, make the comparison depending on the argument max 
 
     index = i; 
 
    } 
 
    return index; 
 
} 
 

 
// take an two dimensional array and rearrange it 
 
function reArrange(arr) { 
 
    var simple = arr.reduce(function(acc, a) {     // first let's make the two dimensional array into a one dimensional array 
 
    return acc.concat(a); 
 
    }, []); 
 
    
 
    var result = [];           // the result array 
 
    while(simple.length) {          // while there is element in the one dimensional array 
 
    var min = minMax(simple, false);       // get the min index 
 
    var max = minMax(simple, true);       // get the max 
 
    result.push([           // push the items at the min and max indexes as a sub-array of the result array 
 
     simple.splice(min, 1)[0],        // splice to remove it from simple array as well 
 
     simple.splice((max < min)? max: max - 1, 1)[0]   // if max index is after min index then substract one because the above splice shrank the array 
 
    ]); 
 
    } 
 
    return result; 
 
} 
 

 

 

 
var arr = [ 
 
    [{"name":"one","team":"------","checked":false,"position":"-"}, 
 
    {"name":"two","team":"------","checked":false,"position":"1"}], 
 
    [{"name":"three","team":"------","checked":false,"position":"3"}, 
 
    {"name":"four","team":"------","checked":false,"position":"7"}] 
 
]; 
 

 
console.log(reArrange(arr));

0

Вы можете использовать сортировки внутренний массив, а затем присвоить результат и сортировки снова.

var data = [[{ "name": "one", "team": "------", "checked": false, "position": "-" }, { "name": "two", "team": "------", "checked": false, "position": "1" }], [{ "name": "three", "team": "------", "checked": false, "position": "3" }, { "name": "four", "team": "------", "checked": false, "position": "7" }]], 
 
    result = []; 
 

 
data.forEach(function (a) { 
 
    a.sort(function (a, b) { return (+b.position || Number.MIN_VALUE) - (+a.position || Number.MIN_VALUE); }); 
 
}); 
 

 
data.forEach(function (a, i) { 
 
    a.forEach(function (b, j) { 
 
     result[j] = result[j] || []; 
 
     result[j][i] = b; 
 
    }); 
 
}); 
 

 
result.forEach(function (a) { 
 
    a.sort(function (a, b) { return (+a.position || Number.MAX_VALUE) - (+b.position || Number.MAX_VALUE); }); 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }