Matthew Sirkin Matthew Sirkin - 11 months ago 37
Javascript Question

Checking the lengths of all my arrays in Javascript

My goal is to have a bunch of arrays, para1, para2.... para20, and find all of the arrays with multiple elements in it, and then to be able to access them. For example I want an if statement in a for loop that would basically check all of my arrays to see which ones have multiple elements. Then, for the ones that do have multiple elements I would use an if statement to extract a particular item from each array.

var para1 = ["NB4-CAXL-14U-12-"]
var para2 = ["K"]
var para3 = ["-270°C to 1372°C, –454°F to 2501°F"]
var para4 = ['1/8"', '3/16"', '1/4"'];
var para5 = ['6"', '12"', '18"'];

for (var j = 1; j < 10; j++) {
var lenId = "para" + j;

document.getElementById("demo").innerHTML = typeof lenId;

I defined a few arrays and made a for loop that generated a variable that was the name of each of the arrays, but when i went to check the length of the arrays i realized they are all 5, because lenId = "para1" is just a string with 5 letters in it. How would i be able to check para1 to see how many elements are in the array? Or is there a better method for checking the length of all my arrays by possibly putting them all into one larger array or something? Any help would be greatly appreciated

Answer Source

Put the arrays in an object:

var O = {
  para1: ["NB4-CAXL-14U-12-"],
  para2: ["K"],
  para3: ["-270°C to 1372°C, –454°F to 2501°F"],
  para4: ['1/8"', '3/16"', '1/4"'],
  para5: ['6"', '12"', '18"']

for(var j in O) {
  console.log(j + ': ' + O[j].length);