andrewplummer / Sugar

A Javascript library for working with native objects.
https://sugarjs.com/
MIT License
4.53k stars 306 forks source link

Is there something for sorting arrays by multiple items? #599

Open Costegillio opened 7 years ago

Costegillio commented 7 years ago

Greetings!

I can't find any info in official (docs) for sorting multidimensional arrays by multiple items with choosing sorting direction.

So, i wrote this function: `
window.sortByMultiple = function(arr, field1, direction1, field2, direction2){

    arr.sort(function (a, b) {

        var field1A = a[field1];
        var field1B = b[field1];

        var field2A = a[field2];
        var field2B = b[field2];

        if (field1A === field1B) {

            if (direction2 == "down") {
                return (field2A > field2B) ? -1 : (field2A < field2B) ? 1 : 0;
            } else {
                return (field2A < field2B) ? -1 : (field2A > field2B) ? 1 : 0;
            }

        } else {

            if (direction1 == "down") {
                return (field1A > field1B) ? -1 : (field1A < field1B) ? 1 : 0; 
            } else {
                return (field1A < field1B) ? -1 : (field1A > field1B) ? 1 : 0;
            }

        }

    });

}

` If it's could be usefull, feel free to use it in sugar. If sugar already has something like that, please help me to find it.

andrewplummer commented 7 years ago

This looks like a good candidate for a plugin. Have a look at the readme here.

Costegillio commented 7 years ago

Sorry, i haven't time for it. Anyway, thanks for your project!

andrewplummer commented 6 years ago

Will give this some consideration for the next version. Thanks