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!
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.
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)
In typescript 2.1 you'll be able to do:
function OrderByArray<T, K extends keyof T>(values: T[], orderType: K) {
...
}
More about keyof.
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