---
title: "Comment by Darlan Tódero ten Caten on \"5 useful tips about the JavaScript array sort method\" | Hashnode"
description: "Very well explained, thank you! To contribute here is a compare function I use to sort objects by an property name: export const dynamicSortByProperty = ( prope"
url: "https://hashnode.com/posts/5-useful-tips-about-the-javascript-array-sort-method/5f76f70c9c3b6e410121591e/comment/5f7781a97d160d41227d6ea6"
---

[Discussion](https://hashnode.com/posts/5-useful-tips-about-the-javascript-array-sort-method/5f76f70c9c3b6e410121591e)

Comment [5 useful tips about the JavaScript array sort method](https://hashnode.com/posts/5-useful-tips-about-the-javascript-array-sort-method/5f76f70c9c3b6e410121591e)

[Darlan Tódero ten Caten](https://hashnode.com/@darlantc)

[Oct 2, 2020](https://hashnode.com/posts/5-useful-tips-about-the-javascript-array-sort-method/5f76f70c9c3b6e410121591e/comment/5f7781a97d160d41227d6ea6)

Very well explained, thank you!

To contribute here is a compare function I use to sort objects by an property name:

```
export const dynamicSortByProperty = (property: string, asc = true) => {
  const sortOrder = asc ? 1 : -1;
  return (a, b) => {
    if (!a.hasOwnProperty(property) || !b.hasOwnProperty(property)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA =
      typeof a[property] === "string" ? a[property].toUpperCase() : a[property];
    const varB =
      typeof b[property] === "string" ? b[property].toUpperCase() : b[property];

    const result = varA < varB ? -1 : varA > varB ? 1 : 0;
    return result * sortOrder;
  };
};
```

[Tapas Adhikary](https://hashnode.com/@atapas)

[Oct 3, 2020](https://hashnode.com/posts/5-useful-tips-about-the-javascript-array-sort-method/5f76f70c9c3b6e410121591e/comment/5f7781a97d160d41227d6ea6#reply-5f77ed997d160d41227d7139)

[Darlan Todero ten Caten](https://hashnode.com/@darlantc), Thank you very much for adding to it. Awesome!
