Utilizing a sort function as described earlier, you can arrange a numeric array in a random order.
Example
const points = [40, 100, 1, 5, 25, 10]; points.sort(function(){return 0.5 – Math.random()}); |
Objects are commonly found within JavaScript arrays.
Example
const cars = [ {type:“Volvo”, year:2016}, {type:“Saab”, year:2001}, {type:“BMW”, year:2010} ]; |
Even when objects possess properties of varying data types, the sort() method can still be employed to sort the array.
The solution involves crafting a compare function to compare the property values.
Example
cars.sort(function(a, b){return a.year – b.year}); |
String property comparisons entail a slightly more intricate process.
Example
cars.sort(function(a, b){ let x = a.type.toLowerCase(); let y = b.type.toLowerCase(); if (x < y) {return –1;} if (x > y) {return 1;} return 0; }); |