Search code examples
typescriptsortingangular7

Sorting an array of objects based on string property in Typescript


I have an array of objects like so:

0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}

And I need to sort the array of objects based on the 'name' property.

I have searched around for the answer and have tried each of them out but with no joy. The two main answers I came across were:

Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });

and

Array.sort((a, b) => a.name.localeCompare(b.name))

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.

Full code:

getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }

Solution

  • The issue was that I was doing the sort too late! If you need to edit a collection in anyway and you are using a subscribe to fill your collection then add the code within the subscribe!

    I did not include my full code at first which is what caused confusion as the answers supplied all worked. This is a good example of why you should include full code.