Sorting of array in JavaScript using the sort functionality

   

Hey guys once again welcome to the Decoders blog, I hope you all are doing well and today I'm present with another logic but this time we will sort an array using the sort functionality of the JavaScript and will also learn about the various types of the sort functionaliy .......

// Functionless
sort()

// Arrow function
sort((a, b) => { /* … */ } )

// Compare function
sort(compareFn)

// Inline compare function
sort(function compareFn(a, b) { /* … */ })
compareFunction(a, b) return valuesort order
> 0sort a after b
< 0sort a before b
=== 0
keep original order of a and b

       

//Sorting an array in JS=====using the inbuilt sorting libraries
var array=[1,4,5,78,3,2,90];

array.sort();
console.log(array);    //This will sort the array in ascending order

//For sorting the array in a different way we need to pass a function inside the
sort function separately
var array=[1,4,5,78,3,2,90];

array.sort((a,b)=>{
    if(a>b){
        return -1;
    }
    else
        return 1;
});
console.log(array);    //This time the array will be sorting in a descending order

Comments

Popular Posts