1

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?

1

1 Answer 1

1

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) )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.