Sorting a list of values using comparator function in Javascript

 A = [3, 8, 7, 5] B = [3, 1, 7, 19]

A.sort((a,b)=>a-b) //sorting a single array
console.log(A)
let list=[]
for(let i=0;i<A.length;i++){
    list.push([A[i],B[i]])
}
console.log(list) //creating a list from two arrays


// let A=[[2,9],[3,3],[1,5],[3,6],[3,9]] --generating a list from two arrays
// console.log(A)


//code to sort the list of elements using comparator function
//It will compare the first element in the array,
//if two elements are equal then it will compare the next element in the array.
list.sort((a,b)=>{
    // console.log(a[1])
    if(a[0]>b[0]){
        return 1
    }else
    if(a[0]<b[0]){
        return -1
    }else
    if(a[0]==b[0]){
        if(a[1]>b[1]){
            return -1
        }
        else{
            return 1
        }
    }
})


//here we are sorting the first element in ascending order,
// if both numbers are same then we are sorting the second element in decending order.


refer: mdn docs sort function for more details

Comments

  1. reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    ReplyDelete

Post a Comment

Popular Posts