Trier un array en Javascript

Publié dans Snippet | Marqué avec , ,
Share

Simple sort

var myArray = ["var2", "var1", "var3"];
console.log("Before:", myArray); // Output: "Before: ["var2", "var1", "var3"]"
myArray.sort();
console.log("After:", myArray); // Output: "After: ["var1", "var2", "var3"]"

More complex sort

var myComplexArray = [{"id":"3", "data":"var2"}, {"id":"2", "data":"var1"}, {"id":"1", "data":"var3"}];
console.log("Before:", myComplexArray ); // Output: "Before: [{"id":"3", "data":"var2"}, {"id":"2", "data":"var1"}, {"id":"1", "data":"var3"}]"
myComplexArray .sort(function(a, b){ return a.id < b.id; });
console.log("After:", myComplexArray ); // Output: "After: [{"id":"1", "data":"var3"}, {"id":"2", "data":"var1"}, {"id":"3", "data":"var2"}]"

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *