【问题标题】:How to add array with distinct elements and add the repetitive elements value using javascript如何添加具有不同元素的数组并使用javascript添加重复元素值
【发布时间】:2018-11-13 12:25:11
【问题描述】:

我有一个包含值的数组

myarray=["Mark:40", "John:20", "Sofia: 60", "Mark:30"]

desiredArray=["Mark:70", "John:20", "Sofia: 60"]

它应该检查名称是否唯一,如果多次找到相同的名称,它应该添加标记并使用不同的元素制作所需的数组。我能够获得唯一的数组,但无法合并标记。有人可以帮忙吗?

【问题讨论】:

    标签: javascript jquery sharepoint sharepoint-online


    【解决方案1】:

    您可以使用Map 来收集值并为结果呈现新字符串。

    var array = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"],
        result = Array.from(
            array.reduce(
                (m, s) => (([k, v]) => m.set(k, (m.get(k) || 0) + +v))(s.split(/:\s*/)),
                new Map
            ).entries(),
            a => a.join(':')
        );
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      您可以使用reduce 对数组进行分组。使用Object.entries 将对象转换为数组,使用map 形成所需的输出。

      let myarray = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"];
      
      let desiredArray = Object.entries(myarray.reduce((c, v) => {
        let [n, a] = v.split(':');
        c[n] = c[n] || 0;
        c[n] += +a;
        return c;
      }, {})).map(o => o[0] + ":" + o[1]);
      
      console.log(desiredArray);

      【讨论】:

        【解决方案3】:

        您也可以选择使用简单的for 循环:

        var myarray=["Mark:40", "John:20", "Sofia: 60", "Mark:30"];
        for(var i=0; i<myarray.length; i++){
          var splitVal = myarray[i].split(":");
          var nameI = splitVal[0];
          var scoreI = parseInt(splitVal[1]);
          for(var j=i+1; j<myarray.length; j++){
            splitVal = myarray[j].split(":");
            var nameJ = splitVal[0];
            if(nameI === nameJ){
              scoreI += parseInt(splitVal[1]);
              myarray.splice(j,1);
            }
          }
           myarray[i] = nameI+":"+scoreI;
        }
        console.log(myarray);

        【讨论】:

          【解决方案4】:

          一个简单的方法是每次您想要添加一个新值并检查该键是否存在时都遍历新数组。如果它确实增加值,如果不增加它。

          这是一个带有临时对象的解决方案。

          // Initial array
          const myarray = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"]
          // Temporary object used to calculate values
          const desired = {};
          
          for (let value of myarray) {
            // Index of the first digit in the string
            const separatorIndex = value.indexOf(':') + 1;
            // Key is everything before the first digit including the :
            let key = value.substr(0, separatorIndex);
            // If the key isn't present in the object add it
            if (desired[key] === undefined) {
              desired[key] = 0;
            }
            // Add the value of the key to the temporary object
            // this combines the values of equal keys
            desired[key] += parseFloat(value.substr(separatorIndex));
          }
          
          const desiredArray = [];
          // Create an array from all values
          for (let key in desired) {
            desiredArray.push(key + desired[key].toString());
          }
          
          console.log(desiredArray);

          【讨论】:

            【解决方案5】:

            你可以这样做:

            const array = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"];
            const temp = array.reduce((a, c, i, arr) => {
              const u = c.split(':');
              a[u[0]] = a[u[0]] + +u[1] || +u[1];
              return a;
            }, {});
            const result = Object.keys(temp)
              .map(u => `${u}:${temp[u]}`);
            
            console.log(result);

            【讨论】:

              猜你喜欢
              • 2015-12-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-03-13
              • 1970-01-01
              • 2014-05-26
              • 1970-01-01
              相关资源
              最近更新 更多