sort items in array by asc in Javascript
Code snippet on how to sort items in array by asc in Javascript
const arr = [3,2,10,9,1,2];
arr.sort(function(a, b){
return a - b
});
This code snippet is to sort items in an array in ascending order. It begins by creating an array with the numbers 3, 2, 10, 9, 1, and 2. The next line uses the sort() method to arrange the array in ascending order. The anonymous function within the sort() method determines how to sort the array. In this case, it is using the subtraction operator to compare two elements of the array and determine which one is greater than the other. The “a - b” returns a negative number if “a” is less than “b”, a positive number and if “a” is greater than “b”, and 0 if “a” equals “b”. This allows the sort() method to move elements around within the array until it is ordered correctly from least to greatest.