Sort array based on intermediate model's attribute

273 Views Asked by At

I have three models (I am using Vue/Vuex-ORM on the frontend). Category, CategoryItem and Item.

I'm able to fetch an array of categories, and within each category is an array of items. An intermediate join model defines the relationships of these two models, and I am able to access as such:

// array of categories, each category has array of items
const categories = Category.query().where('pack_id', this.selectedPack.id).with('items').get();

categories.map(category => {
    category.items.forEach(item => {
        console.log('item.pivot: ', item.pivot); // pivot refers to join model
        // how to order items based on item.pivot?
    })
})

Within the .forEach, I can access the join model with item.pivot. What I am looking to do however, is sort each category's items based on item.pivot.position.

I started going down a path where the first line inside of the .map I defined a new empty array, and would then theoretically push in a new value based on whether the position was higher or lower, but I couldn't quite wrap my head around how to accomplish this.

Thanks!

1

There are 1 best solutions below

0
On

Well just my luck. A half hour after posting this question, I figure it out! Here was what I did, in case anyone is curious.

categories() {
    const categories = Category.query().where('pack_id', this.selectedPack.id).with('items').get();

    categories.forEach(category => category.items.sort(this.compare));
    return cats;
}

compare(a, b) {
    let comparison = 0;
    if (a.pivot.position > b.pivot.position) comparison = 1;
    else if (a.pivot.position < b.pivot.position) comparison = -1;
    return comparison;
},