Damit können wir eine Schlüsselfunktion übergeben, die für die Sortierung verwendet wird
Array.prototype.sortBy = function(key_func, reverse=false){
return this.sort( (a, b) => {
var keyA = key_func(a),
keyB = key_func(b);
if(keyA < keyB) return reverse? 1: -1;
if(keyA > keyB) return reverse? -1: 1;
return 0;
});
}
Wenn wir also zum Beispiel Folgendes haben
var arr = [ {date: "01/12/00", balls: {red: "a8", blue: 10}},
{date: "12/13/05", balls: {red: "d6" , blue: 11}},
{date: "03/02/04", balls: {red: "c4" , blue: 15}} ]
Wir können
arr.sortBy(el => el.balls.red)
/* would result in
[ {date: "01/12/00", balls: {red: "a8", blue: 10}},
{date: "03/02/04", balls: {red: "c4", blue: 15}},
{date: "12/13/05", balls: {red: "d6", blue: 11}} ]
*/
oder
arr.sortBy(el => new Date(el.date), true) // second argument to reverse it
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}},
{date: "03/02/04", balls: {red: "c4", blue:15}},
{date: "01/12/00", balls: {red: "a8", blue:10}} ]
*/
oder
arr.sortBy(el => el.balls.blue + parseInt(el.balls.red[1]))
/* would result in
[ {date: "12/13/05", balls: {red: "d6", blue:11}}, // red + blue= 17
{date: "01/12/00", balls: {red: "a8", blue:10}}, // red + blue= 18
{date: "03/02/04", balls: {red: "c4", blue:15}} ] // red + blue= 19
*/