Function to sort items with an array of keys I'm working on a function to sort two elements using several properties. I want to know if the function is well structured.

function comparePropsOfAWithB(a, b, props) {
    var prop  = props[0];
    var propA = a[prop];
    var propB = b[prop];

    if (propA === propB) {
        var array = props;
        array.shift();
        return props.length ? comparePropsOfAWithB(a, b, props) : false
    } else if (propA &lt; propB ) {
        return true
    } else {
        return false
    }
}


This function is meant to be used alongside the sort method like this:

array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })


The intent of the function is to compare two objects using several values to determine if they are different. In the example, the key "a" will be tested, and if it fails, "b" will be tested until the last element of the array is reached.
That's not how the comparison function for Array.sort() works at all: it should return negative, zero, or positive.

Eating up all or part of the props argument (due to your array.shift() call) is bad practice.

The usage is cumbersome:


array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })



Wouldn't it be nicer to write a propertyComparator(…) function that returns a function?

array.sort(propertyComparator('a', 'b', 'c'))


Something like this:

function propertyComparator() {
    var props = arguments;
    return function(a, b) {
        for (var i = 0; i &lt; props.length; i++) {
            var aProp = a[props[i]];
            var bProp = b[props[i]];
            if (aProp &lt; bProp) return -1;
            if (aProp &gt; bProp) return +1;  
        }
        return 0;
    };
}