2

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

Community
  • 1
  • 1
Dhinakar
  • 4,061
  • 6
  • 36
  • 68
  • @Tushar Included my expected output, can you get my question? – Dhinakar Feb 05 '16 at 04:09
  • Given the field you are sorting on is a string ending with a % character your sort function needs to convert the values to numbers for a numeric sort. Use parseFloat(), it'll automatically ignore the %. – nnnnnn Feb 05 '16 at 04:14
  • @nnnnnn I can able to convert this to number. Its not a problem. even I change i unable to do the sort. that's my issue. :( – Dhinakar Feb 05 '16 at 04:15
  • That's _very difficult_ for me. Is sorting that difficult. We've thousands of sorting questions on SO, even searching is also difficult. [`arr.sort((a, b) => +b[1].replace('%', '') - +a[1].replace('%', ''))`](https://jsfiddle.net/tusharj/gc3r00qv/) – Tushar Feb 05 '16 at 04:15

2 Answers2

4

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;
    }
}
mylee
  • 1,293
  • 1
  • 9
  • 14
  • Looks good, works. But why are you using `==`? I'd suggest using `===` since we're comparing primitives; most linting tools will complain at this. – yangmillstheory Feb 05 '16 at 04:19
3

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]);
});
choz
  • 17,242
  • 4
  • 53
  • 73