0

I have an array of arrays, each nested array contains an object with 2 values: good and bad.

[
    0:[
        count:{

            good: 5,
            bad: 3
        }
    ],
    1:[
        count:{

            good: 7,
            bad: 6
        }
    ],
    2:[
        count:{

            good: 0,
            bad: 8
        }
    ],
    3:[
        count:{

            good: 0,
            bad: 9
        }
    ],
    4:[
        count:{

            good: 4,
            bad: 1
        }
    ]
]

I'd like to order the array in descending order from high to low by good and then when good is 0, order the rest of arrays in descending order from high to low by bad. So the resulting array would look like this:

[
    0:[
        count:{

            good: 7,
            bad: 6
        }
    ],
    1:[
        count:{

            good: 5,
            bad: 3
        }
    ],
    2:[
        count:{

            good: 4,
            bad: 1
        }
    ],
    3:[
        count:{

            good: 0,
            bad: 9
        }
    ],
    4:[
        count:{

            good: 0,
            bad: 8
        }
    ]
]

I'm using Underscore and am a little confused as to how to best approach this as there are two values I want to sort by and they are within an object within the nested arrays.

Using sortBy seems to be the obvious choice, but I'm not sure how to first sort by good and then by bad.

sortBy _.sortBy(list, iterator, [context])

Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length).

Daft
  • 10,277
  • 15
  • 63
  • 105
  • Those aren't arrays. You've used array initializers (`[...]`), but they used property names as though they were object properties, not array entries. They might be objects, it's hard to tell from the question. Show valid JavaScript code for creating the structure, so there's no ambiguity about what the structure is. – T.J. Crowder Jun 22 '16 at 10:48
  • As of the edits, that's still not valid JavaScript syntax, and you're still showing things as though they were arrays that I suspect probably aren't. Again: Post valid initializers showing the format, so there's no question what the format is. – T.J. Crowder Jun 22 '16 at 10:50

2 Answers2

1

With a proper array, you could use Array#sort with a custom callback.

var array = [{ count: { good: 5, bad: 3 } }, { count: { good: 7, bad: 6 } }, { count: { good: 0, bad: 8 } }, { count: { good: 0, bad: 9 } }, { count: { good: 4, bad: 1 } }];

array.sort(function (a, b) {
    return b.count.good - a.count.good || b.count.bad - a.count.bad;
});

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Actually your question was answered before you asking. here is an enhanced way to do the thing.

Community
  • 1
  • 1
Morteza Tourani
  • 3,506
  • 5
  • 41
  • 48