Avec cela, nous pouvons passer une fonction clé à utiliser pour le tri.
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;
});
}
Alors, par exemple, si nous avons
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}} ]
Nous pouvons faire
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}} ]
*/
ou
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}} ]
*/
ou
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
*/