将多维数组中的所有整数相加 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33665228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:46:09  来源:igfitidea点击:

Sum all integers in a multidimensional array javascript

javascriptarraysloopsmultidimensional-arraysum

提问by VoA

Let's say I have this:

假设我有这个:

function arrSum(){
  *code here*
}

How do I write the arrSum function such that it can sum all the integers within a multidimensional array (of variable depth).

我如何编写 arrSum 函数,以便它可以对多维数组(可变深度)中的所有整数求和。

I.e.

IE

arrSum([2, 5, [4, 6], 5]) === 22;

I know there must be an answer to this somewhere but I really can't find it. If this is a duplicate please let me know.

我知道某个地方一定有这个问题的答案,但我真的找不到。如果这是重复的,请告诉我。

回答by Pranav C Balan

Simply you can write a function like this with recursion

只需您可以使用递归编写这样的函数

function arrSum(arr) {
  var sum = 0;
  // iterate array using forEach, better to use for loop since it have higher performance
  arr.forEach(function(v) {
    // checking array element is an array
    if (typeof v == 'object')
      // if array then getting sum it's element (recursion)
      sum += arrSum(v);
    else
      // else adding the value with sum
      sum += v
  })
  // returning the result
  return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);

Using forloop

使用for循环

function arrSum(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] == 'object')
      sum += arrSum(arr[i]);
    else
      sum += arr[i];
  }
  return sum;
}

console.log(arrSum([2, 5, [4, 6], 5]) === 22);

回答by ryanpcmcquen

A more modern approach using .reduce():

使用更现代的方法.reduce()

const arr = [2, 5, [4, 6], 5];

const arrSum = array =>
    array.reduce(
        (sum, num) => sum + (Array.isArray(num) ? arrSum(num) : num * 1),
        0
    );

console.log(arrSum(arr));

回答by Anshuman

Check this:

检查这个:

function arrSum(objArr){
  var total = 0;
  for(var outerLoop=0; outerLoop < objArr.length; outerLoop++){
    if(objArr[outerLoop].constructor === Array){
      for(var innerLoop=0; innerLoop < objArr[outerLoop].length; innerLoop++){
        total += objArr[outerLoop][innerLoop];
      }
    } else {
      total += objArr[outerLoop];
    }
  }
  return total;
}

alert (arrSum([2, 5, [4, 6], 5]));

回答by DevDeb

    function arrSum(arr) {
        var totalSum = null;
        var numString = arr.toString();
        var numberArray = numString.split(",");
        numberArray.forEach(function(ele){
          totalSum = totalSum + parseInt(ele);
        });
        return totalSum;
    }
    console.log(arrSum([2, 5, [4, 6], 5]);

回答by Safia Nuzhath

If we have a multi-dimensional array with strings and integers and we have to get the sum of the numbers, then following @Pranav C Balan's solution we could add a check in the else loop to check only for digits as below -

如果我们有一个包含字符串和整数的多维数组并且我们必须得到数字的总和,那么按照@Pranav C Balan 的解决方案,我们可以在 else 循环中添加一个检查以仅检查数字,如下所示 -

      function arrSum(arr) {
    var sum = 0;
    for (var i = 0; i < arr.length; i++) {
      if (typeof arr[i] == 'object'){
         sum += arrSum(arr[i]);
      }else if (Number(arr[i])){
         sum += arr[i];
      }
    }
    return sum;
  }
  console.log(arrSum([2, 'a', 5, [4, 6, 10, [1, 2, 'b'], 10], 5]));

回答by Tomer W

I would build a function similar to what Pranav C Balanwith the difference that i would check the isObject()before calling forEach(),
This way i get around problems posed by sending a single numericparameter, or Nullvalues.

我会构建一个类似于Pranav C Balan的函数,不同之处在于我会isObject()在调用之前检查它forEach()
这样我就可以解决发送单个numeric参数或Null值带来的问题。

function arrSum(v) {
  // checking if element is an array
  if (typeof v == 'object') {
    var sum = 0;
    
    // iterate array using forEach, better to use for loop since it have higher performance
    v.forEach(function(e) {
      sum+=arrSum(e);
    });
    return sum;
  }
  else {
      return v;
  }
}
$('body').append($('<p></p>').html('[2, 5, [4, 6], 5] = ' + arrSum([2, 5, [4, 6], 5])));
$('body').append($('<p></p>').html('[2,, 5] = ' + arrSum([2,, 5])));
$('body').append($('<p></p>').html('5 = ' + arrSum(5)));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by Penny Liu

This can be done with lodash _.flattenDeepand _.sum:

这可以通过 lodash_.flattenDeep_.sum

var arr = [2, 5, [4, 6], 5];
arrSum(arr);

function arrSum(arr) {
  var arrFlattens = _.flattenDeep(arr);
  // => [2, 5, 4, 6, 5]
  console.log(_.sum(arrFlattens));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>