【问题标题】:JavaScript: Split array into groups (array of arrays) based on equal valuesJavaScript:根据相等的值将数组拆分为组(数组数组)
【发布时间】:2016-08-09 08:41:19
【问题描述】:

我正在尝试做这个练习:

挑战在于实现一个将所有的函数加在一起的函数 数组中的连续数字并将它们推送到新数组中。 例如: sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]); // -> [2,2,4,2,3]

我的想法是将数组拆分为数组数组。所以对于上面的例子:[[1,1],[2],[1,1,1,1],[2],[1,1,1]] 然后通过 reduce 他们。

我已经尝试将while 循环和push 放入一个临时变量中,如果下一个数字不相同,则该变量会被推送,但无济于事。

关于如何实现这一点的任何想法?

【问题讨论】:

  • 你想让我们做你的功课吗?请分享您的代码。我们将帮助您修复错误,但我们不是您的代码工厂。
  • 到目前为止你取得了什么成就?请粘贴您的代码 sn-p,如果您有的话,以帮助您改进它。
  • 请将代码带入工作室
  • @Randy 不。我询问了有关“如何实现这一目标”的想法。我让你帮我写出来吗?无论哪种方式,代码传入
  • var reducer = a => a.reduce((p,c,i,a) => (i === 0 ? p[0] = c : c == a[i-1] ? p[p.length-1] += c : p[p.length] = c,p),[])

标签: javascript arrays


【解决方案1】:

我能想到的最简单的方法...(不过没有 map/reduce)

var sumConsecutives = function(arr) {
var newArr = [];
var prev = arr[0];
var sum = arr[0];

for (var i=1; i<arr.length; i++){
	if (arr[i] !== prev) {
		newArr[newArr.length] = sum;
		sum = 0;
	}
	sum += arr[i];
	prev = arr[i];
}

// Add last sum
newArr[newArr.length] = sum;

return newArr;
};

console.log ( sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]) );
	

【讨论】:

    【解决方案2】:

    您可以使用一步reduce 方法:

    const sumConsecutives = ar =>
    ar.reduce((ac, x, i) => {
      if ( i !== 0 && ar[i-1] === x)
        ac[ac.length -1] += x;
      else 
        ac.push(x);
        
      return ac;
     }, [])
    
    
    var r = sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]); // -> [2,2,4,2,3]
    
    console.log(r)

    【讨论】:

    【解决方案3】:

    我喜欢这个挑战,所以我把它做成了一个你认为有用的两步函数。

    • 第一个reduce创建数组数组

    • 第二个 reduce 将它们相加。

    这不是最短的代码,但我希望是最容易理解的。

    const arr = [1,1,2,1,1,1,1,2,1,1,1];
    let currentNumber = undefined;
    let currentTempArr = [];
    
    let newArr = arr.reduce((tempArr, value) => {
      // check if current number is set
      if(currentNumber == undefined) currentNumber = value;
      
      // if current number then push to temp array
      if(currentNumber == value)
        currentTempArr.push(value);
      // else just create a new array and push the old one into the parent array
      else {
        tempArr.push(currentTempArr);
        currentTempArr = [];
        currentNumber = value;
        currentTempArr.push(value);
      }
      
      // return the array back to the next reduce iteration
      return tempArr;
    }, []);
    
    // push the last temp array, because the function stops before the push
    newArr.push(currentTempArr);
    
    // this build your array of arrays
    console.info('The array of arrays');
    console.log(newArr); // [ [1,1,1], [2], ... ]
    
    // now sum up the sub arrays
    let sumArr = newArr.reduce((tempArr, value) => {
      let sum = 0;
      
      // for every value in the array we add that to the sum
      value.forEach(val => sum += val);
      
      // add the total to the temp array
      tempArr.push(sum);
      
      // return the filled array back to the reduce function
      return tempArr;
    }, []);
    
    // the array with summed up values
    console.info('see the magic happen');
    console.log(sumArr);

    【讨论】:

      【解决方案4】:
      function sumConsecutives(input) {
          var output = [],
              factor = 1,
              lastnr = null;
      
          for (var i = 0; i < input.length; i++) {
              if (i === 0) {
                  lastnr = input[i];
                  continue;
              }
      
              if (input[i] !== lastnr) {
                  output.push(lastnr * factor);
                  lastnr = input[i];
                  factor = 1;
              } else {
                  factor++;
              }
      
              if (i === (input.length - 1)) {
                  output.push(input[i] * factor);
              }
          }
          return output;
      }
      
      var result = sumConsecutives([1,1,2,1,1,1,1,2,1,1,1]);
      

      【讨论】:

        【解决方案5】:

        您可以使用array.reduce

        逻辑

        • 创建一个临时数组。
        • 遍历数组并检查之前的值和当前值。
        • 如果相同,则取 temp 数组的最后一个元素并将当前值添加到其中。
        • 如果不是,则将当前元素推送到临时数组

        样本

        function sumConsecutives(arr) {
          var r = [];
          arr.reduce(function(p, c, i, a) {
            if (p === c) {
              r[r.length - 1] += c
            } else {
              r.push(c)
            }
            return c;
          }, 0);
          return r;
        }
        var a = [1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1];
        console.log(sumConsecutives(a));

        【讨论】:

          【解决方案6】:

          这是我能想到的最简单的:

          var testarr = [1,1,2,1,1,1,1,2,1,1,1];
          var resultarr = [testarr[0]];
          for(var i=1; i<testarr.length; i++){
          	if(testarr[i-1]==testarr[i]){
          		resultarr[resultarr.length - 1] += testarr[i];
          	}else{
          		resultarr.push(testarr[i]);
          	}
          }
          console.log(resultarr);

          【讨论】:

            【解决方案7】:

            你也可以试试这个方法:

            var source = [1,1,2,1,1,1,1,2,1,1,1];
            
            source.reduce(function(p, c, index, arr) {                 
               if (p.length === 0 || arr[index - 1] !== c) {
                   return p.concat(c);
               }
               else if (arr[index - 1] === c) {           
                    p[p.length - 1] += c             
               }
            
               return p;
            }, []);
            

            【讨论】:

              猜你喜欢
              • 2011-06-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-09-17
              • 1970-01-01
              • 2013-12-04
              • 2021-01-27
              • 2022-11-12
              相关资源
              最近更新 更多