

The typeof operator is also used to check the data type of the property’s value. the objects remain unchanged with respect to each other). If it’s not defined on both objects, the function returns 0, which causes the sort order to remain as is (i.e. In the code above, the hasOwnProperty method is used to check if the specified property is defined on each object and has not been inherited via the prototype chain. sort ( compareValues ( 'born', 'desc' ) ) sort ( compareValues ( 'name' ) ) // array is sorted by date if birth in descending order sort ( compareValues ( 'band', 'desc' ) ) // array is sorted by name in ascending order

sort ( compareValues ( 'band' ) ) // array is sorted by band in descending order We’ll cover the specifics of how compare functions work later in this article.įor this demo we’ll use an array of singers and sort them by their band names alphabetically: const singers = [ return ( (order = 'desc' ) ? (comparison * - 1 ) : comparisonĪnd this is how you’d use it: // array is sorted by band, in ascending order by default They allow us to sort arrays of objects by strings, integers, dates, or any other custom property. A compareFunction applies rules to sort arrays by defined our own logic. To sort an array of objects, use the sort() method with a compare function. How to Sort an Array of Objects in JavaScript
