user3126180
user3126180

Reputation:

sort array of arrays in specific order using lodash

I want to sort an array of arrays based on:

  1. Parameter given manually
  2. Then sorted by DESC

Here is the array

var ar = [
    [{'name' : 'b', 'val' : '1'}, {'name' : 'b', 'val' : '10'}], // 'name' are always the same
    [{'name' : 'a', 'val' : '2'}, {'name' : 'a', 'val' : '2'}],
    [{'name' : 'c'}, {'name' : 'c', 'val' : '100'}]
]

When the sorting function is executed: sortBy('a')

It should return me:

var ar = [
    [{'name' : 'a', 'val' : '2'}, {'name' : 'a', 'val' : '2'}], 
    [{'name' : 'c'}, {'name' : 'c', 'val' : '100'}]
    [{'name' : 'b', 'val' : '1'}, {'name' : 'b', 'val' : '10'}],
]

Because 'a' is given as a parameter, it has priority. Then it is sorted from Z to A.

Solution should be written is ES5 (using lodash if possible).

Upvotes: 0

Views: 1011

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386644

You could tried the one at top different from the others for sorting descending.

const
    sortBy = value => ([{ name: a }], [{ name: b }]) =>
        (b === value) - (a === value) ||
        b.localeCompare(a),
    array = [[{ name: 'b', val: '1' }, { name: 'b', val: '10' }], [{ name: 'a', val: '2' }, { name: 'a', val: '2' }], [{ name: 'c'}, { name: 'c', val: '100' }]];

array.sort(sortBy('a'));

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

ES5

var sortBy = function (value) {
        return function (a, b) {
            return (b[0].name === value) - (a[0].name === value)
                || b[0].name.localeCompare(a[0].name);
        };
    },
    array = [[{ name: 'b', val: '1' }, { name: 'b', val: '10' }], [{ name: 'a', val: '2' }, { name: 'a', val: '2' }], [{ name: 'c'}, { name: 'c', val: '100' }]];

array.sort(sortBy('a'));

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

Upvotes: 2

user3126180
user3126180

Reputation:

thanks to @NirAlfasi Advice, I found a way to do it:

function customSort(arr, sortBy, priority){
    var sortAZ = function(a,b){return (a[0][sortBy] < b[0][sortBy]) ? -1 : (a[0][sortBy] > b[0][sortBy]) ? 1 : 0;}
    var sortPrior = function(a,b){if(b[0][sortBy] === priority ){return 1} else {return 0}}

    arr.sort(sortAZ).reverse().sort(sortPrior);
}
customSort(ar,'name','a')

console.log(ar);

Upvotes: 0

Related Questions