我正在为一个销售应用程序开发后端部分,其中我有两个对象数组,一个是卖家名称,另一个是每月销售额.

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}];

这是我已经try 过的:

const bestSellers= () => {
  sales.reduce((sum, value) => ( value.sellerId == 1 ? sum + value.area : sum), 0); }

最终结果应如下所示:

const sellers= [{id:3,name: 'apolo', age: 45},{id:2,name: 'adrian', age: 32},{id:1,name: 'juan', age: 23}]

推荐答案

你想在这里做两件事.

  1. 找到每个卖家的总销售额.
  2. 对每个卖家的总销售额进行排序.

在我的排序功能中,您可以看到我正在按卖家筛选所有销售.

一旦我得到了一个卖家的销售额,我就使用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))

Javascript相关问答推荐

模块与独立组件

Google Apps脚本中的discord邀请API响应的日期解析问题

被CSS优先级所迷惑

了解Node.js中的EventEums和浏览器中的addEventEums之间的关系

Plotly热图:在矩形上zoom 后将zoom 区域居中

自定义高图中的x轴标签序列

Promise Chain中的第二个useState不更新

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

在使用REACT更改了CSS类之后,无法更改CSS样式

让chart.js饼图中的一个切片变厚?

按下单键和多值

如果一个字符串前面有点、空格或无字符串,后面有空格、连字符或无字符串,则匹配正则表达式

如果NetSuite中为空,则限制筛选

为什么NULL不能在构造函数的.Prototype中工作

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?

在Reaction Native中,ScrolltoIndex在结束时不一致地返回到索引0

如何使用Angular JS双击按钮

此上下文在JavaScript中

Oracle APEX-如何调用Java脚本函数

动画可以在Chrome上运行,但不能在Safari上运行