Answer the question
In order to leave comments, you need to log in
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];
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);
Answer the question
In order to leave comments, you need to log in
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);
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'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question