0

I want to load data from api and then parse it into bootstrap rows. I have an array finalData which contains 15 strings, I need to parse it to create a bootstrap rows/cards

I am trying this but first time number of elements are coming up to be 5 as the index starts from 0. What additional condition do I need to use?

let finalData = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","i"];

finalData.forEach((element, index) => {

        index == 0 ? mhtml += `<div class="row">` : null;
        mhtml += `<div class="col-sm-3">
                    finalData[index]
                </div>`;
        index != 0 && index % 4 == 0 ? mhtml += `</div><div class="row">` : null;
    });

This is giving me following result: I don't need 5 element in first row I need 4 in all.

<div class="row>
a
b
c
d
e
</div>
<div class="row>
f
g
h
i
</div>
<div class="row>
j
k
l
m
</div>
<div class="row>
n
i
</div>
<div class="row>

I need result to be:

<div class="row>
a
b
c
d
</div>
<div class="row>
e
f
g
h
</div>
<div class="row>
i
j
k
l
</div>
<div class="row>
m
n
i
</div>
0

2 Answers 2

1

you're checking when modulo 4 is zero, but this will be your 5th element. try using (index + 1) % 4 instead

Sign up to request clarification or add additional context in comments.

Comments

1

You are correct, the results fit the index - your first pass through is grabbing index values 0,1,2,3,4 which is 5 rows. Your second pass is grabbing 5 6, 7, 8 which fits your requirements. You just need to check for (index + 1) % 4

index != 0 && ((index + 1) % 4) == 0 ? mhtml += `</div><div class="row">` : null;

Comments

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.