Jamie McElwain
Jamie McElwain

Reputation: 462

Custom sort in JS

I'm trying to sort an array of objects into a custom order - that is, one where the sort is not logic based but arbitrary.

I currently have it working like this:

sortedAssessments() {
  return [
    this.assessments.find(assessment => assessment.id === 14),
    this.assessments.find(assessment => assessment.id === 15),
    this.assessments.find(assessment => assessment.id === 4),
    this.assessments.find(assessment => assessment.id === 17)
  ]
}

But running Array.find 4 times seems quite expensive. Is there a way this could be achieved using Array.sort?

Upvotes: 1

Views: 330

Answers (1)

gurvinder372
gurvinder372

Reputation: 68413

Make a priority array

var priority = [14, 15, 4, 17];

Now sort as per this priority using indexOf

sortedAssessments() {
     return this.assessments.sort( (a, b) => priority.indexOf(a.id) - priority.indexOf(b.id) )
}

Upvotes: 1

Related Questions