Skip to content Skip to sidebar Skip to footer

Sort 2 Array By Column, As A Parameter In A Function

I can sort an array by column with this answer It looks a bit like this: var myArr = [ [0, 10, 20, 'jam'], [1, 20, 14, 'carrots'], [2, 30, 14, 'custard'], [3, 40, 16, 'beef'],

Solution 1:

Let's have some functional programming here:

constcmp = (a, b) => (a > b) - (a < b)
constcolumn = p => o => o[p]
constby = f => (x, y) =>cmp(f(x), f(y))


myArr = [
    [0, 10, 20, "jam"],
    [1, 20, 14, "carrots"],
    [2, 30, 14, "custard"],
    [3, 40, 16, "beef"],
    [4, 0, 16, "gwen"],
]

myArr.sort(by(column(2)));
console.log(myArr.map(JSON.stringify))


myArr.sort(by(column(3)));
console.log(myArr.map(JSON.stringify))

A less "advanced", but perhaps more readable (and ES3 compatible) version:

functionsortByColumn(arr, col) {
    return arr.sort(function(x, y) {
        x = x[col]
        y = y[col]
        return (x > y) ? 1 : (x < y ? -1 : 0)
    })
}

Solution 2:

You could take a closure over the index and return the sorting function as callback.

var sortByIndex = function (index) {
        returnfunction (a, b) {
            return (a[index] > b[index]) - (a[index] < b[index]);
        };
    },
    array = [[0, 10, 20, "jam"], [1, 20, 14, "carrots"], [2, 30, 14, "custard"], [3, 40, 16, "beef"], [4, 0, 16, "gwen"]];

array.sort(sortByIndex(1));
console.log(array);

array.sort(sortByIndex(3));
console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Sort 2 Array By Column, As A Parameter In A Function"