Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have two arrays if "Cost" and "Sell" price about many fruits. How calculate the diference using a "smart" function filter and map?

in Vue3 composition API, I have 2 arrays 
const fruitsSellerPrice = [
{id: 1, name: apple, priceSeller: '10.90'},
{id: 2, name: banana, priceSeller: '11.20'},
{id: 3, name: orange, priceSeller: '12.30'},
{id: 4, name: framboesa, priceSeller: '13.90'}}];

const fruitsBuyPrice = [
{id: 1, name: apple, priceBuy: '6.90'},
{id: 2, name: banana, priceBuy: '6.20'},
{id: 3, name: orange, priceBuy '7.30'},
{id: 4, name: framboesa, priceBuy: '16.90'}}];

I would like to know how can I do a "smart" filter that return te difference by "name" and order High to low or Low to High, priceSell – PriceBuy…

I have me a function with very big lines.. something is wrong….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try something like following snippet:

const fruitsSellerPrice = [{id: 1, name: 'apple', priceSeller: '10.90'},{id: 2, name: 'banana', priceSeller: '11.20'},{id: 3, name: 'orange', priceSeller: '12.30'},{id: 4, name: 'framboesa', priceSeller: '13.90'}]

const fruitsBuyPrice = [{id: 1, name: 'apple', priceBuy: '6.90'},{id: 2, name: 'banana', priceBuy: '6.20'},{id: 3, name: 'orange', priceBuy: '7.30'},{id: 4, name: 'framboesa', priceBuy: '16.90'}]

let sortOrder = true
const res = fruitsSellerPrice.map(f => {
  return {...f, diff: Math.abs((Number(f.priceSeller) - Number(fruitsBuyPrice.find(u => u.id === f.id).priceBuy))).toFixed(2)}
}).sort((a, b) => {
  return sortOrder ? a.diff - b.diff : b.diff - a.diff
})

console.log(res)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading