【问题标题】:Adding string-number pairs to an array (from array), so that recurring strings increment the number instead of being added again将字符串-数字对添加到数组(来自数组),以便重复字符串增加数字而不是再次添加
【发布时间】:2020-05-21 08:28:47
【问题描述】:

如何以某种方式从(项目-编号对)数组中插入项目,以便如果已添加项目,我们会增加与项目关联的数字?

所以当我们第一次添加项目时,我们将与其关联的数字设置为 1。

我这样做的原因是有一个项目列表,其中包含它们在输入数组中出现的次数。

如果有更好的方法来接收该结果,我也很乐意接受这些答案。

【问题讨论】:

    标签: javascript arrays algorithm object associative-array


    【解决方案1】:

    在 Python 中,您可以使用字典(在某些其他语言中称为 map)来完成此操作。

    li = ['Item#1', 'Item#2', 'Item#3', 'Item#1', 'Item#4', 'Item#1']
    
    dict_map = {}  # we can also use defaultdict
    
    for item in li:
        dict_map[item] = dict_map.get(item, 0) + 1
    
    print(dict_map)
    

    输出:

    {'Item#1': 3, 'Item#2': 1, 'Item#3': 1, 'Item#4': 1}
    

    您可以使用与此等效的 JavaScript。

    【讨论】:

      【解决方案2】:

      let array = ['apple', 'cherry', 'orange'];
      
      let res = {};
      
      array.forEach(x => res[x] = 0);
      
      function add(item) {
        res[item]++;
        document.getElementById(item).innerHTML = res[item]++;
      
        console.log(res);
      }
      <div>Apple <span id="apple">0</span></div>
      <div>Cherry <span id="cherry">0</span></div>
      <div>Orange <span id="orange">0</span></div>
      
      <button onclick="add('apple')">addApple</button>
      <button onclick="add('cherry')">addCherry</button>
      <button onclick="add('orange')">addOrange</button>

      【讨论】:

      猜你喜欢
      • 2012-12-15
      • 1970-01-01
      • 2021-03-10
      • 2016-08-02
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      相关资源
      最近更新 更多