javascript sorting by value code example
Example 1: how to sort an array by value in javascript
arr.sort(function(a, b){return a-b});
arr.sort((a, b) => a - b);
arr.sort(function(a, b){return b - a});
arr.sort((a, b) => b - a);
Example 2: sorting in js
var arr = [23, 34343, 1, 5, 90, 9]
var sortedArr = [];
arr.forEach(x => {
if (sortedArr.length == 0)
sortedArr.push(x)
else {
if (sortedArr[0] > x) sortedArr.unshift(x)
else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
}
})
console.log(sortedArr);
console.log(arr.sort((a,b)=>{
return a-b;
}));