Answers for "sort th array in javascrpit"

0

how to sort an array in javascript

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); // for ascending
//another way for ascending
points.sort((a,b)=>{
  if(a>b){
      return 1
  }else if(a<b){
      return -1
  }else{
      return 0
  }
})
points.sort(function(a, b){return b - a}); // for descending
//another way for descending
points.sort((a,b)=>{
  if(a>b){
      return -1
  }else if(a<b){
      return 1
  }else{
      return 0
  }
})
Posted by: Guest on August-23-2021
1

sorting in js

var arr = [23, 34343, 1, 5, 90, 9]

//using forEach
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);


// using sort method
console.log(arr.sort((a,b)=>{
    return a-b;
}));
Posted by: Guest on February-25-2021

Browse Popular Code Answers by Language