简体   繁体   中英

Javascript, sort array alphabetically and nest each alphabet

I am currently working on an ionic2 project. I am getting data in an array, and I have to show it as a contact list style with side alphabet navigation. Please refer the image attached.

The data structure is somewhat like this

[
{"id":1,"first_name":"Harcourt"},
{"id":2,"first_name":"Cart"},
{"id":3,"first_name":"Laina"},
{"id":4,"first_name":"Deborah"},
{"id":5,"first_name":"Kendricks"}
]

I am able to sort array by first_name using lodash. But I could not figure out how to show that sorted array using *ngFor in angular2, so that every time alphabet changes (from A -> B eg), the first element can be given a unique id, so that when user tap on side bar alphabet I can scroll to that element.

Please help. Should I create some nested array for this?

样本图片

You can try something like this :

 let input = [ { id: 2, first_name: "Cart" }, { id: 4, first_name: "Deborah" }, { id: 6, first_name: "Dobby" }, { id: 1, first_name: "Harcourt" }, { id: 5, first_name: "Kendricks" }, { id: 6, first_name: "Lenny" }, { id: 3, first_name: "Laina" } ], people = [] let firstLetter = "" for(let i in input) { let currentLetter = input[i].first_name[0].toUpperCase() if(currentLetter!=firstLetter) { firstLetter = ""+currentLetter people.push({ index : firstLetter}) } people.push(input[i]) } console.log(people) 

Then in your template, conditionally display either a name or an index :

<li *ngFor="let p of people">
    <div *ngIf="p.first_name; else listIndex">
       {{p.firstName}}
    </div>

    <ng-template #listIndex>
        <div class="list-index">
           {{p.index}}
        </div>
    </ng-template>
<li>

link this:

let input = [
    { id: 1, first_name: "Harcourt" },
    { id: 2, first_name: "Cart" },
    { id: 3, first_name: "Laina" },
    { id: 4, first_name: "Deborah" },
    { id: 5, first_name: "Kendricks" },
    { id: 6, first_name: "Dobby" },
    { id: 7, first_name: "Lenny" },
];

input.sort(function(a, b) {
    var nameA = a.first_name.toUpperCase();
    var nameB = b.first_name.toUpperCase();

    if(nameA < nameB) {
        return -1;
    }

    if(nameA > nameB) {
        return 1;
    }

    return 0;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM