Issue
I’m developing the backEnd part for a selling app in which I have 2 Array of Objects, one got the sellers’ name, and the other has the monthly sales.
I was told by my superiors to order the Array of names from the one that made the most sales to the one that made the least ( from highest to lowest ) using the data from the array which contains the sales, basically making a summation of the key => quantity.
I’m not sure how to do it, I tried to use a Reduce method with the sales of each seller but I can’t think how to compare them to reorganize the Array.
The code is:
const sellers= [{id:1,name: 'juan', age: 23},{id:2,name: 'adrian', age: 32},{id:3,name: 'apolo', age: 45}];
const sales= [{equipo: 'frances', sellerId: 2, quantity: 234},{equipo: 'italiano', sellerId: 3, quantity: 24},{equipo: 'polaco', sellerId: 1, quantity: 534},{equipo: 'frances', sellerId: 2, quantity: 1234},{equipo: 'frances', sellerId: 3, quantity: 2342}];
This is what I have already tried:
const bestSellers= () => {
sales.reduce((sum, value) => ( value.sellerId == 1 ? sum + value.area : sum), 0); }
The final result should look like this:
const sellers= [{id:3,name: 'apolo', age: 45},{id:2,name: 'adrian', age: 32},{id:1,name: 'juan', age: 23}]
Solution
You’re trying to do two things here.
- Find the total sales for each seller.
- Sort the total sales for each seller.
Inside my sort function you can see I am filtering all of the sales by the seller.
Once I have just the sales for one seller I use the reduce method to sum the quantity of their sales into an easy to use number.
Then I’m comparing the previous sellers quantity to the current sellers quantity to re-order them using the sort method.
I encourage you to read the documentation of the methods used so you understand what is happening at each step.
Methods used:
Sort
Filter
Reduce
const sellers = [{
id: 1,
name: 'juan',
age: 23
}, {
id: 2,
name: 'adrian',
age: 32
}, {
id: 3,
name: 'apolo',
age: 45
}];
const sales = [{
equipo: 'frances',
sellerId: 2,
quantity: 234
}, {
equipo: 'italiano',
sellerId: 3,
quantity: 24
}, {
equipo: 'polaco',
sellerId: 1,
quantity: 534
}, {
equipo: 'frances',
sellerId: 2,
quantity: 1234
}, {
equipo: 'frances',
sellerId: 3,
quantity: 2342
}];
const expected = [{
id: 3,
name: 'apolo',
age: 45
}, {
id: 2,
name: 'adrian',
age: 32
}, {
id: 1,
name: 'juan',
age: 23
}]
const result = sellers.sort((a, b) => {
totalA = sales.filter(sale => sale.sellerId === a.id).reduce((acc, val) => acc + val.quantity, 0)
totalB = sales.filter(sale => sale.sellerId === b.id).reduce((acc, val) => acc + val.quantity, 0)
return totalB - totalA
})
// Check we get what we expect
console.log(JSON.stringify(expected) === JSON.stringify(result))
Answered By – Daniel Tate
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0