Tapas Adhikary
Educator @tapaScript | Founder CreoWis & ReactPlay - Writer - YouTuber - Open Source
JavaScript arrays are an ordered collection that can hold data of any type. Arrays are created with square brackets [...] and allow duplicate elements. In JavaScript, we can sort the elements of an array with the built-in method called, sort(). In th...
blog.greenroots.info11 min read
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;
};
};
Sort method is one of my favourite array methods. Thank you for the write-up. 😊
Christopher Norris
good game, good choice
This is wonderful and helpful information.