Home > database >  How to get the least cost element from an array in Vue
How to get the least cost element from an array in Vue

Time:09-29

I have item.warehouse_positions array which has several prices and IDs, but I need to view only one item.id with lowest price. How can I do it?

<div v-for='(item, index) in item.warehouse_positions' :key='index'>
 {{ item.id }} -- {{ item.price }}
</div>

CodePudding user response:

const lowestItem = item.warehouse_positions.sort((x, y) => x.price - y.price)[0];

Sort your objects by price and take out the first one, which should be the cheapest.

In Vue, your best bet is to make a computed property that returns this object.

CodePudding user response:

Create a computed property

computed:{
   getLowestItem(){
    return this.<YOUR_ARRAY_IN_DATA>.sort((a,b)=>a.price-b.price)[0]   
  }
}

Display it in your template

<div>"{{getLowestItem}}"</div>
  • Related