javascript - 如何将数组的值与产品和值相加并从最小到最大排序?
问题描述
我是 JavaScript 的初学者,我正在渲染一个包含一些产品的列表。
一个产品包含多个尺寸,每个尺寸都有其价格。
我想知道如何汇总每种产品不同尺寸的价格。按升序排列,从小到大。
我想要的是,例如,加入所有尺寸product 1
以获得总值,将所有尺寸相加product 2
并获得总值等等。之后,按升序排列所有产品。
我尝试使用该reducer
功能。但在每个产品内部,它都包含一个具有各自尺寸和价格的数组。我不知道该怎么做。
我把我的代码放进了代码沙箱
import React from "react";
import { useStyles } from "./styles";
const Products = (props) => {
const { product } = props;
const classes = useStyles();
return (
<div
style={{
display: "flex",
flexDirection: "row",
marginBottom: "10px"
}}
>
<span style={{ fontWeight: 600, marginBottom: "10px" }}>
Sizes:{" "}
<span style={{ fontWeight: 300 }}>
{product.sizes.map((cat) => (
<div className={classes.boxItem}>
<span className={classes.boxFooterName}>{cat.name}</span>
<span className={classes.boxFooterPrice}>
{cat.price !== 0
? (cat.price / 100).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
: "Free"}
</span>
</div>
))}
</span>
</span>
</div>
);
};
export default Products;
先感谢您。
解决方案
对于我会做的价格总和:
const prices = {};
data.forEach(({ sizes }) => {
sizes.forEach(({ name, price }) =>
prices[name] ? (prices[name] += price) : (prices[name] = price)
);
});
console.log(prices);
并按升序对数据进行排序:
const compareElements = (product1, product2) => {
const product2Sizes = product2.sizes.map(({ name }) => name);
const firstMatchingSize = product1.sizes.find(
({ name }) => product2Sizes.includes(name) && name !== "Sample"
);
const product2Size =
firstMatchingSize &&
product2.sizes.find(({ name }) => name === firstMatchingSize.name);
return firstMatchingSize &&
product2.sizes &&
firstMatchingSize.price > product2Size.price
? 1
: -1;
};
const sortedProducts = data.sort(compareElements);
推荐阅读
- spring - 如何对子属性中包含的 ID 进行复杂的 @PreAuthorize 检查?
- rust - 具有可变引用的递归结构中的生命周期
- templates - 在生产站点中为 getTemplate lsit 调用 Docusign API 失败?
- rundeck - 有没有办法使用非登录用户来运行 Rundeck 作业?
- php - WampServer, mysqli_connect (HY000/1045) 拒绝用户访问
- javascript - 无法读取 null 的属性“角色”
- javascript - 从 HTML 输入中获取日期以在 JS 中使用
- mysql - 优化二级索引和日期范围查询
- scala - 尝试失败时的短路映射操作
- c# - 我的 NLog 记录没有保存。我在哪里可以看到我的 NLog 保存失败?