Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript nested arrays with strings

I have an array that contains another array as well as strings:

var text;
var languageSet = ["Language4", "Language5"];
var languages = [
        ["Language1", "Language2", "Language3"],
        languageSet,
        "Language6"
    ];

(function selector() {
    for (i = 0; i < languages.length; i++) {
        for (j = 0; j < languages[i].length; j++) {
            text += "<option value='" + languages[i][j] + "'>" + languages[i][j] + "</options>";
        }
    }
    document.getElementById("languageOptions").innerHTML = text;
})();

HTML:

<select id="languageOptions">
</select>

But everytime I run this, the output for "Language 6" ends up being as such:

L
a
n
g
u
a
g
e

6

How do I output that as an entire string? I don't know why my code doesn't work for strings and arrays inside arrays.

like image 516
montybird Avatar asked Apr 15 '26 13:04

montybird


1 Answers

You should do a type check to see if your item is an array and then loop the array. I used Array.isArray here to do that type check. The code example is working for you to test.

The Array.isArray() method returns true if an object is an array, false if it is not.

var text;
var languageSet = ["Language4", "Language5"];
var languages = [
        ["Language1", "Language2", "Language3"],
        languageSet,
        "Language6"
    ];


(function selector() {
    for (i = 0; i < languages.length; i++) {
      if (Array.isArray(languages[i])) {
        for (j = 0; j < languages[i].length; j++) {
          
            text += "<option value='" + languages[i][j] + "'>" + languages[i][j] + "</options>";
        }
      } else {
        text += "<option value='" + languages[i] + "'>" + languages[i] + "</options>";
      }
    }
    document.getElementById("languageOptions").innerHTML = text;
})();
<select id="languageOptions">
</select>
like image 170
Enkode Avatar answered Apr 18 '26 06:04

Enkode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!