Reputation:
I want to sort an array of arrays based on:
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
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
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