Clasificación de matrices multidimensionales

I have a multi-dimensional array in javascript defined as :-

myArray[0][0] = Some IMage;
myArray[0][1] = Some price;
myArray[0][2] = Some name;
myArray[0][3] = Some values;
myArray[0][4] = Some otherValues;
myArray[1][0] = Some IMage;
myArray[1][1] = Some price;
myArray[1][2] = Some name;
myArray[1][3] = Some values;
myArray[1][4] = Some otherValues;

Now my job is to sort them according to the price . How can this be done ?

preguntado el 09 de marzo de 12 a las 23:03

I would say, don't use a multi-dimensional array like that. Have an array of objects which store the info and then sort the objects. -

How to use object for storing the values ? Should I save the values as myArray[0]["image"] = some Image; ..etc ? -

Debería ser algo como var arr = []; arr.push({ img: '', price: 99, name: 'Name', values: 123, otherValues: 987 }); Let's say you pushed multiple objetos into this array. Then you can access the first object's price by arr[0].price y el segundo por arr[1].price. -

Ok Thanks ! I will implement this :D -

You have two arrays with price values in them myArray[0] y myArray[1]. Do you want each array sorted separately? Do you want all price values sorted together and then replaced with the first 5 values in one array and the last 5 values in the second array? How do you want it sorted? We can't answer the question without knowing this. -

5 Respuestas

Per my comment above, you should probably use objects instead of multi-dimensional arrays. Here's an example (imagine your additional attributes like name y IMage included, which I didn't include for the sake of less typing)

var arr = [
    { price: 12, something: 'a b c' },
    { price: 8, something: 'a b c' },
    { price: 45, something: 'a b c' },
    { price: 10, something: 'a b c' }
];

arr.sort(function(a, b) { return a.price - b.price; });

/*
    arr is now:

    [ 
        { price: 8, something: 'a b c' },
        { price: 10, something: 'a b c' },
        { price: 12, something: 'a b c' },
        { price: 45, something: 'a b c' } 
    ]
*/

respondido 10 mar '12, 00:03

Just a small doubt. How will I create the object above given I have the values in 5 different arrays ? - Prashant Singh

what do you mean five diff arrays? What does each array store? - Marshall

First one has the price, second one has the name n so n so . I just wish to say given the values How can I make such object ? In other words, How to push tha values into object - Prashant Singh

así que si tienes var names = ['Tim', 'Prashant'] y var prices = [12, 25] tu puedes hacer var arr = []; for(var i = 0, l = names.length; i < l; i++) { arr.push({ name: names[i], price: prices[i] }); } and then sort. Does that work with what you mean? - Marshall

That script requires that the separate arrays are the same length. It loops based on the names array. Which is not bullet-proof. And won't be as long as you have to work with these disconnected arrays. - Marshall

Here's the answer without judgement of the data structure in case someone searches the question. "Improper" structure like this is sometimes needed (eg: as input for dataTables).

arr.sort(function(a, b) { return a[1] - b[1]; });

respondido 10 mar '12, 00:03

Arrays have a sort function that accepts another function as comparator. You can sort your data like this:

var comparator= function(a,b){
   var price1 = a[1], price2=b[1]; // use parseInt() if your "price" are quoted 
   if( price1 < price2) return -1;
   else return 1;
   return 0;
};
myArray.sort(comparator);

respondido 10 mar '12, 00:03

Borrowed from Marshall.

var myArray = [];
myArray.push({
    image: 'some image',
    price: 1.5,
    name: 'name',
    values: 'values',
    otherValues: 'otherValues'
});

myArray.push({
    image: 'some image2',
    price: 0.5,
    name: 'name2',
    values: 'values2',
    otherValues: 'otherValues2'
});

myArray.push({
    image: 'some image3',
    price: 2.5,
    name: 'name3',
    values: 'values3',
    otherValues: 'otherValues3'
});

myArray.sort(function (a, b) {
    return a.price - b.price;
});

alert(myArray[0].price);
alert(myArray[1].price);
alert(myArray[2].price);

respondido 10 mar '12, 00:03

Javascript Multi-Criteria / Multi-Parameter Sort

If you want to sort an array by a single value, or by multiple-values you can define the following function:

function sortByCriteria(data, criteria) {
    return data.sort(function (a, b) {

        var i, iLen, aChain, bChain;

        i = 0;
        iLen = criteria.length;
        for (i; i < iLen; i++) {        
            aChain += a[criteria[i]];
            bChain += b[criteria[i]];
        }

        return aChain.localeCompare(bChain);
    });
}

Then invoke like this:

var data = [
    { price: 12, something: 'a b c' },
    { price: 8, something: 'a b c' },
    { price: 45, something: 'a b c' },
    { price: 10, something: 'a b c' }
];
var criteria = ["price", "something"];

sortByCriteria(data, criteria);

http://jsfiddle.net/oahxg4u3/6/

Respondido el 19 de diciembre de 14 a las 23:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.