【问题标题】:Storing the quantity of values from an array into another array将数组中的值的数量存储到另一个数组中
【发布时间】:2021-03-05 20:14:27
【问题描述】:

我有两个数组,一个包含重复值,另一个为空:

let cart = [7, 7, 15, 21];
let quantity = [];

如何获取值在购物车数组中出现的次数并将其推送到数量数组,从而得到如下结果:

quantity = [2, 1, 1]

在哪里: 购物车数组中的 7 是数量数组中的 2,数量数组中的 15 和 21 分别是 1。

【问题讨论】:

  • 如果数组末尾还有另外一个 7 怎么办?你想要[3, 1, 1] 还是[2, 1, 1, 1]?顺便说一句,你试过什么?
  • 我想要 [3, 1, 1]。我尝试了 for 循环和数组方法 forEach,但它们给了我不同的结果。 forEach 方法接近了,它给了我 [1, 2, 1, 1] 而不是 [2, 1, 1] 的结果。

标签: javascript arrays loops push


【解决方案1】:

您可以使用 Map 来保存商品在购物车中出现的次数,然后使用它来获取所需形式的数组

const cartItemsMap = new Map();

let cart = [7, 7, 15, 21, 7];

cart.forEach(item => cartItemsMap.set(item, (cartItemsMap.get(item) || 0) + 1));

let quantity = [...cartItemsMap.values()];

console.log(quantity); // [3, 1, 1] in the same order as of your cart items

我们不能在这里使用对象,因为对象不会按我想你想要的顺序保持键

【讨论】:

    【解决方案2】:

    一种对对象进行闭包以保持索引的方法。

    const
        cart = [7, 7, 15, 21],
        result = [];
    
    cart.forEach((indices => v => {
        if (v in indices) result[indices[v]]++;
        else indices[v] = result.push(1) - 1;
    })({}));
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      您可以使用.reduce 迭代cart,同时使用Map 存储每个数字的出现次数。最后,你会返回这张地图的values

      const getOccurences = (cart=[]) =>
        cart.reduce((quantity,num) => {
          const count = 1 + (quantity.get(num) || 0);
          quantity.set(num, count);
          return quantity;
        }, new Map).values();
      
      console.log( ...getOccurences([7, 7, 15, 21, 7]) );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多