Categories
TypeScript Answers

How to sort an array of objects in TypeScript?

Spread the love

Sometimes, we want to sort an array of objects in TypeScript.

In this article, we’ll look at how to sort an array of objects in TypeScript.

How to sort an array of objects in TypeScript?

To sort an array of objects in TypeScript, we can use the array sort method like we do with JavaScript.

For instance, we write

const sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {
  if (obj1.value > obj2.value) {
    return 1;
  } else if (obj1.value < obj2.value) {
    return -1;
  }
  return 0;
});

to call unsortedArray.sort with a callback to sort the entries in the array and return it.

We compare the value of the value property in each object.

And we return 1, -1, or 0 depending if we want to put obj2 before obj1, obj1 before obj2 or keep the items in the same order respectively.

unsortedArray is unchanged after calling sort, it returns a new array with the sorted entries.

Conclusion

To sort an array of objects in TypeScript, we can use the array sort method like we do with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *