Skip to content Skip to sidebar Skip to footer

Javascript 2d Array Sorting - By Numerical Value

I've seen another couple of posts similar to this question, but none work for my scenario and at a lost how to solve this (such as Sort a 2D array by the second value) I will expla

Solution 1:

I would like this in a 2D array

sorted["Stock B, 1000","Stock C, 900", "Stock D, 800", "Stock A, 200"]

That's not a 2D array, that's a single dimensional array of strings. This would be a 2D array:

sorted = [["Stock B", 1000], ["Stock C", 900], ["Stock D", 800], ["Stock A", 200]];

...which you can sort by the second value like this:

sorted.sort(function(a, b) {
    var avalue = a[1],
        bvalue = b[1];
    if (avalue < bvalue) {
        return -1;
    }
    if (avalue > bvalue) {
        return1;
    }
    return0;
});

But you may be better off with a single-dimensional array of objects:

sorted= [
    {name:"Stock B", quantity:1000},
    {name:"Stock C", quantity:900},
    {name:"Stock D", quantity:800},
    {name:"Stock A", quantity:200}
];

...which you can sort like this:

sorted.sort(function(a, b) {
    var avalue = a.quantity,
        bvalue = b.quantity;
    if (avalue < bvalue) {
        return -1;
    }
    if (avalue > bvalue) {
        return1;
    }
    return0;
});

Post a Comment for "Javascript 2d Array Sorting - By Numerical Value"