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"}]"

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*