首页 > 解决方案 > 如何将数组的值与产品和值相加并从最小到最大排序?

问题描述

我是 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;

先感谢您。

标签: javascriptreactjs

解决方案


对于我会做的价格总和:

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);

推荐阅读