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

Viewed 2629

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
}
5 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.

It's synchronous. Callback itself doesn't mean owner function is asynchronous. Callback is just for deciding how to sort. So you can put your next logic outside of callback safely.

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

.sort() is a function from the JavaScript language, and it is determined to be synchronous by the ECMAScript specification.

(Functions of the node.js framework are ususally asynchronous by default, but .sort() is coming from JavaScript language itself, not from the node.js framework.)

It is very likely that you want to use it asynchronously, when it comes to any production level application. You can:

  • just wrap it around an asynchronous function scope, or
  • write your own asynchronous implementation, or
  • you can find several ready-to-use implementations for this issue, for example as an npm package.

You are right, you need to pay attention that the code which is counting on the sorting to be done needs to be executed after sorting. If you have chosen the first option in the 3 options before, you can:

  • put stuff inside one and only callback (likely minor things), or
  • build up a callback chain with .then()
  • use the await keyword as you have mentioned.

Please note that I didn't want to confuse you with so many solutions, but it's necessary to be aware of them. They will become second nature over time. If all of this feels a little confusing at this moment, I'd suggest you to start with the basic .sort() wrapped around an asynchronous function, and chained with .then() functions.


EDIT

As my peer mentioned above, .sort() itself does not accept a callback function, but a sorting function instead. That is correct. In order to use .sort() asynchronously, you have to wrap it around your own asynchronous function, as I've suggested.

Modify input is a bad idea and you don't need await to make sure data.sort is synchronous, just declare a new variable to hold the result of sort like:

var sorted_data = data.sort(function(a,b){
  return new Date(b.updateddate) - new Date(a.updateddate);
})
var nomination_group_id = _.groupBy(sorted_data, "submissionid")
Related