I need to sort by array, and if the two elements are equal, then I need to do a secondary sort on a different key inside these elements. Taking a look at the Mozilla Developer Network docs for array.sort , there is a good piece of code below to handle the first view. I liked it because it was concise and shows how you can write powerful JS.
Here is what I tried based on code from MDN. This correctly makes the first appearance.
var list = [{name:'Delta', ref: 456}, {name:'Delta', ref: 123}, {name:'alpha', ref: 789}, {name:'CHARLIE', ref: 012}, {name:'bravo', ref: 345}];
var mapped = list.map(function (el, i) {
return {
index: i,
value: el.name.toLowerCase(),
secondaryValue: el.ref
};
});
mapped.sort(function (a, b) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});
var result = mapped.map(function (el) {
return list[el.index];
});
console.log(list);
console.log(result);
Now I know that I can change a comparison function like this to fulfill the secondary sort requirement:
mapped.sort(function (a, b) {
if (a.value === b.value){
return +(a.secondaryValue > b.secondaryValue) || +(a.secondaryValue === b.secondaryValue) - 1;
}
return +(a.value > b.value) || - 1;
});
But for me it loses some of the charm return +(a.value > b.value) || +(a.value === b.value) - 1;- it's pretty cool, in my opinion.
: ?
: Pure JS. ES5 , , ES6 .