简体   繁体   中英

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, ie, 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

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;
    }
}

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]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM