Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Sort generic array

I'm trying to implement a function in typescript where the user can pass an array of objects and a property of one of the objects and return the list order by the property the user have chosen.

function OrderByArray(values: any[], orderType: any) { 
    //TODO: implement code
    return values;
} 

Is any way to do it? I know how to sort an array but I don't know how to allow to send the typeof object and order by it.

Thanks!

like image 231
gon250 Avatar asked Jul 20 '26 04:07

gon250


1 Answers

You can use the Array.sort method:

function OrderByArray(values: any[], orderType: any) { 
    return values.sort((a, b) => {
        if (a[orderType] < b[orderType]) {
            return -1;
        }

        if (a[orderType] > b[orderType]) {
            return 1;
        }

        return 0
    });
}

I'm not sure what's the value of item[orderType], so you might need to change the ifs.


Edit

Using it:

let animals = [{ name: "cat" }, { name: "dog" }, { name: "lion" }];
let cars = [{ manufacturor: "ford" }, { manufacturor: "mazda" }, { manufacturor: "fiat" }];

console.log(OrderByArray(animals, "name").map(item => item.name)); // ["cat", "dog", "lion"]
console.log(OrderByArray(cars, "manufacturor").map(item => item.manufacturor)); // ["fiat", "ford", "mazda"]

(code in playground)


2nd Edit

In typescript 2.1 you'll be able to do:

function OrderByArray<T, K extends keyof T>(values: T[], orderType: K) {
    ...
}

More about keyof.

like image 114
Nitzan Tomer Avatar answered Jul 22 '26 02:07

Nitzan Tomer