Dhinakar
Dhinakar

Reputation: 4151

How to Sort Array based on Object Value in JavaScript?

I have an object resultset. It has the below records

var resultset = [{0: "A", 1: "25.14", 2: "0,0,0,0,30.79,0,7.68,0,0,6.13,0,0"}, 
{0: "B", 1: "3.26", 2: "0,0,0,31,0,0,0,0,0,0,0,0"}, 
{0: "C", 1: "37.01", 2: "0,0,0,0,0,0,0,0,0,0,0,0"},  
{0: "D", 1: "1.18", 2: "0,0,0,9.63,0,0,0,0,0,0,0,0"},  
{0: "E", 1: "0.28", 2: "0,0,0,13.22,0,0,0,0,0,0,0,0"}]

I used to sort this object based on value, i.e., Index 1 by using below code,

resultset.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    //alert("A Value -->"+a[1]);
    //alert("B Value -->"+b[1]);
    if (a[1] == b[1]) {

        return 0;
    }
    else {
        //alert(b[1]);
        return (a[1] > b[1]) ? -1 : 1;
        }
   }

But I unable to sort based on index 1.

My expected output is like below sorted based on index 1 (37.01)

{0: "C", 1: "37.01", 2: "0,0,0,0,0,0,0,0,0,0,0,0"}  
{0: "A", 1: "25.14", 2: "0,0,0,0,30.79,0,7.68,0,0,6.13,0,0"} 
{0: "B", 1: "3.26", 2: "0,0,0,31,0,0,0,0,0,0,0,0"} 
{0: "D", 1: "1.18", 2: "0,0,0,9.63,0,0,0,0,0,0,0,0"}  
{0: "E", 1: "0.28", 2: "0,0,0,13.22,0,0,0,0,0,0,0,0"}

I tried to do some object sorting mechanism from below URL. But won't work for me.

http://www.javascriptkit.com/javatutors/arraysort2.shtml

Sorting JavaScript Object by property value

Upvotes: 2

Views: 388

Answers (2)

choz
choz

Reputation: 17898

You're trying to sort a string there.

You should parse the value and do it like,

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

Upvotes: 3

mylee
mylee

Reputation: 1333

You cannot sort a string, just parse as float and then compare

function compareSecondColumn(a, b) {
    var valueA = parseFloat(a[1]);
    var valueB = parseFloat(b[1]);
    if (valueA == valueB) {
        return 0;
    } else {
        return (valueA  > valueB) ? -1 : 1;
    }
}

Upvotes: 4

Related Questions