Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of objects by properties with only one function?

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
}
like image 413
Fray Avatar asked Sep 15 '25 01:09

Fray


1 Answers

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. :-)

like image 184
Krisztián Balla Avatar answered Sep 17 '25 05:09

Krisztián Balla