I
I
Ilya Agafonov2012-08-13 13:52:48
JavaScript
Ilya Agafonov, 2012-08-13 13:52:48

Tricky sorting of a multidimensional array?

There is an array like:

var options = [];
options[1]=['...4','...',4];
options[2]=['...3','...',3];
options[3]=['...5','...',5];
options[5]=['...1','...',1];
options[6]=['...99','...',99];

It is necessary to output these three dots in the order 1,3,4,5,99. The problem is that the id-shki (1,2,3,5,6) needs to be saved, and the usual sorting
function sOrder(a, b) {
if (a[2] > b[2]) return 1;
else if (a[2] < b[2]) return -1;
else return 0;
}
options.sort(sOrder);

kills them. And yes, the id's are out of order.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2012-08-13
@Tairesh

Sorting in any case will change the indexes. Therefore, you do not need to store these id in indexes, but you need to store them in the object itself.
var options = []; options.push({data:['...4','...',4], id : 3}; // и т.д.
Sort like this:
function sOrder(a, b) { if (a.data[2] > b.data[2]) return 1; else if (a.data[2] < b.data[2]) return -1; else return 0; } options.sort(sOrder);

K
Keenest, 2012-08-13
@Keenest

It seems to me easier to do everything through objects. Namely, first parsing a multidimensional array into an array of objects, but sorting an array of objects by the required field is not a problem:

var arr = [];
options.forEach(function (key) {
    var o = {
        first: key[0],
        second: key[1],
        third: key[2]
    };
    arr.push(o);
});

var asc = function (field) { // функция для сортировки в прямом порядке (по возрастанию)
 return function (x, y) {
   return x[field] > y[field];
 }
};

arr.sort(asc('first'));

J
jorikburlakov, 2012-08-13
@jorikburlakov

To be honest, the question is not clear at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question