gon250 gon250 - 1 month ago 18
TypeScript Question

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!

Answer

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)