4

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
}

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.