Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use Array.sort() in synchronous way?

I am not sure whether the Array.sort(callback) is synchronous or asyncronous. But I have used the Array.sort(callback) to sort the date (updateddate which is stored in db as string type) in the following code snippet. Do i need to include await for Array.sort(callback) to ensure that the rest of the code is executed only when the array sorting is completed. Is it right way to use sorting above the synchronous code? Should I write the rest of the code inside the callback of data.sort?

modify_data(data,likesData){
    data.sort(function(a,b){
      return new Date(b.updateddate) - new Date(a.updateddate);
    })
    var nomination_group_id = _.groupBy(data,"submissionid")
    var likes_group
    var refined_arr = [];
    var likesData = likesData
    _.each(nomination_group_id,function(eachObj){
      var mapObj = new Map()
       mapObj.set('category',eachObj[0] ? eachObj[0].question : " ")
       mapObj.set('submitter',eachObj[0] ? eachObj[0].email : " ")
       refined_arr.push([ ...mapObj.values() ])
    })
    return refined_arr
}
like image 953
Prem Avatar asked Oct 23 '18 03:10

Prem


2 Answers

I am not sure whether the Array.sort(callback) is synchronous or asyncronous

  1. Its safe, and its synchronous.
  2. Array.sort(sortFunction) argument sortFunction is synchronously applied on each element of the array. Also, Javascript is single-threaded.

const names = ['adelaine','ben', 'diana', 'carl']

const namesSortedAlphabetically = names.sort() // default is alphabetical sort
console.log('ALPHA SORT', namesSortedAlphabetically)

const namesSortedByLength = names.sort((a, b) => a.length > b.length) // custom sort
console.log('CUSTOM SORT', namesSortedByLength)

Do i need to include await for Array.sort(callback)

Nope, since Array.sort is synchronous and doesn't return a Promise.

like image 62
jonathangersam Avatar answered Nov 13 '22 19:11

jonathangersam


It is safe & synchronous, because it is not a call back, it is just a comparator (compare function) see here

It is not calling this function at the end of doing something, it is using that function. Hope it calrifies

like image 20
Pranoy Sarkar Avatar answered Nov 13 '22 18:11

Pranoy Sarkar