简体   繁体   中英

Count values of the inner two-dimensional array - javascript

I have a two-dimensional array. I'm trying to count the values within the inner array. I'm aware of JS array.length . But doing testData.length yields 5. Which is accurate. However, I want to count the number of items within each sub array.

testData[0].length would yield 6. But how would I dynamically count through each sub array? (as it will change).

var testData = [["column1","test1","test1","tea","party", "water bottle"],
                ["column2","test2","test2","test2 test2"],
                ["column3","test2","test2","test2 test2 "],
                ["column4","test2","test2 test2f asdfsdf"],
                ["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
]

Use reduce :

ES6:

const count = testData.reduce((currentCount, row) => currentCount + row.length, 0);

ES5:

var count = testData.reduce(function(currentCount, row) { 
    return currentCount + row.length;
}, 0);

Documentation : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Use Array.forEach

s=0;
testData.forEach(function(e,i,a){s += e.length; });

See also: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach

var testData = [
    ["column1","test1","test1","tea","party", "water bottle"],
    ["column2","test2","test2","test2 test2"],
    ["column3","test2","test2","test2 test2 "],
    ["column4","test2","test2 test2f asdfsdf"],
    ["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
];
for(var i=0;i < testData.length;i++){
  for(var j=0;j<testData[i].length;j++){
    alert(testData[i][j]);
  }
}

Try adding a new property to the Array object.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=windows-1250">
    <title>New Property</title>
    <script type="text/javascript" language="JavaScript">
      Array.prototype.biLength = function(){
        numItems = 0;
        numRows = this.length;
        for (var i = 0; i < numRows; i++){
          row = testData[i];
          numCols = row.length;
          for (var j = 0; j < numCols; j++){
            numItems++;
          }
        }
        return numItems;
      };
      var testData = [
        ["column1","test1","test1","tea","party", "water bottle"],
        ["column2","test2","test2","test2 test2"],
        ["column3","test2","test2","test2 test2 "],
        ["column4","test2","test2 test2f asdfsdf"],
        ["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
      ];
      alert(testData.biLength());
    </script>
  </head>
  <body>

  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM