I have this Array:
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
]
I want to sort it by the values of color
or size
:
colorSort = () => {
list.sort((a, b) => (a.color > b.color) ? 1 : -1)
}
sizeSort = () => {
list.sort((a, b) => (a.size> b.size) ? 1 : -1)
}
I don't like to create 2 functions for sorting.
Is there any way to create a function like this:
sortArray = (value:string = 'color') => {
#code here
}
You could try this:
function by<T extends keyof U, U>(property: T): (a: U, b: U) => number {
return (a, b) => {
return a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
};
}
const list = [
{ color: 'white', size: 'XXL' },
{ color: 'red', size: 'XL' },
{ color: 'black', size: 'M' }
];
const listSortedByColor = [...list].sort(by("color"));
const listSortedBySize = [...list].sort(by("size"));
Here we use the function by
to create compare functions which can be passed as an argument to the Array.sort method. We can use TypeScript's advanced typing system to make sure that by
is type-safe allowing only properties as arguments that actually exist in the objects you want to sort.
And Remember: Array.sort is in-place. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With