0

what is the best way to generate Html from 2-dimensional array

["red", 2 ]
["blue", 3]
["red", 5 ]
["blue", 1]

output Html

●●
○○○
●●●●●
○

javascript

for(var i = 0; i < arr.length; i++) {
    var result = arr[i][0] == 'red' ? '●' : '○';
    var output = '<tr><td>'+ result +'</td></tr>';
    $('table').append(output);
    for(var j = 0; j < $tArr[i][j].length; l++) {
        // how can I use following 2d data add more balls?
    }
}

not like this:

●
○
●
○

1 Answer 1

3

There's no need to use for loop there, you have number of balls as the second element in the array. Using str.repeat(count):

for(var i = 0; i < arr.length; i++) {
    var ball = arr[i][0] == 'red' ? '●' : '○';
    // 'string'.repeat(N) returns 'string' repeated N times
    var result = ball.repeat(arr[i][1]);
    var output = '<tr><td>'+ result +'</td></tr>';
    $('table').append(output);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man! What if I want to turn to vertical? I will open another quiz.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.