2

While iterating an array I would like to display first two arrays item into first DIV and second two array items into second Div and so on. I have achieved my result partially, but still, I believe this is not correct. How do I achieve this?

I would like to display following arrays items under each div's as below:

First List: Pencil, 200 Rubber, 250 Second List Sharpner, 300 Pen, 400

Third List Paint, 500 Box, 50

<div class="container">
  <div class="best order1" id="one">
    <h1>First List</h1>

  </div>
  <div class="best order2" id="two">
    <h1>Second List </h1>

  </div>
  <div class="best order3" id="three">
    <h1>Third List</h1>

  </div>
  <input type="button" value="List" onclick="myArray();">

</div> 

Below is my function;

function myArray() {

  var arr1 = [];
  arr1 = [{
      "Item": "Pencil",
      "Quantity": 200
    },
    {
      "Item": "Rubber",
      "Quantity": 250
    },
    {
      "Item": "Sharpner",
      "Quantity": 300
    },
    {
      "Item": "Pen",
      "Quantity": 400
    },
    {
      "Item": "Paint",
      "Quantity": 500
    },
    {
      "Item": "Box",
      "Quantity": 50
    }
  ];

  var portion = arr1.length / 2;

  for (i = 0; i < arr1.length; i++) {
    //alert(arr1[i].Item+','+arr1[i].Quantity );
    if (i <= portion) {
      document.getElementById('one').innerHTML += arr1[i].Item + ',' + arr1[i].Quantity + '<br>';

    } else {
      document.getElementById('two').innerHTML += arr1[i].Item + ',' + arr1[i].Quantity + '<br>';

    }

  }

}

This is my Fiddle

0

3 Answers 3

1

One of possible solutions is to add another one nested loop to control the portion of items, and this way you don't need if checks:

for (i = 0; i < arr1.length; i++) {
  for (j = 0; j < portion; j++) {
    document.getElementById('wrapper-'+i).innerHTML += arr1[i*portion+j].Item + ',' + arr1[i*portion+j].Quantity + '<br>';
  }
}

I have also added ids like wrapper-[number] to get access to DOM elements from loop much easier.

Here is JsFiddle

And the snippet:

function myArray() {

  var arr1 = [];
  arr1 = [{
      "Item": "Pencil",
      "Quantity": 200
    },
    {
      "Item": "Rubber",
      "Quantity": 250
    },
    {
      "Item": "Sharpner",
      "Quantity": 300
    },
    {
      "Item": "Pen",
      "Quantity": 400
    },
    {
      "Item": "Paint",
      "Quantity": 500
    },
    {
      "Item": "Box",
      "Quantity": 50
    }
  ];

  var portion = 2;

  for (i = 0; i < arr1.length / portion; i++) {
    for (j = 0; j < portion; j++) {
      document.getElementById('wrapper-'+i).innerHTML += arr1[i*portion+j].Item + ',' + arr1[i*portion+j].Quantity + '<br>';
    }
  }

}
<div class="container">
  <div class="best order1" id="wrapper-0">
    <h1>First List</h1>

  </div>
  <div class="best order2" id="wrapper-1">
    <h1>Second List </h1>

  </div>
  <div class="best order3" id="wrapper-2">
    <h1>Third List</h1>

  </div>
  <input type="button" value="List" onclick="myArray();">
</div>

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

Comments

0

What you can do is. Declare number of sections. portion is a variable that will decide number of sections you want to display the data for. To make it dynamic (in future if you need to change number of sections and if you've more even number of records). And you can do all that within a single loop with basic maths.

Step1 : Get all the section ids by document.querySelectorAll(".best").forEach(e=> ids.push(e.getAttribute("id")) )

Step2 : Declare number of Portions by var portion = arr1.length / 4;

Step3 : Loop through array and append data as html as

 var counter = -1;
arr1.map((e,i)=> {
     if(i%portion == 0)
     counter++;
      document.getElementById(ids[counter]).innerHTML += e.Item +","+e.Quantity+"</br>"

} )

Here is the snippet

function myArray() {

  var arr1 = [];
  arr1 = [{
      "Item": "Pencil",
      "Quantity": 200
    },
    {
      "Item": "Rubber",
      "Quantity": 250
    },
    {
      "Item": "Sharpner",
      "Quantity": 300
    },
    {
      "Item": "Pen",
      "Quantity": 400
    },
    {
      "Item": "Paint",
      "Quantity": 500
    },
    {
      "Item": "Box",
      "Quantity": 50
    },
     {
      "Item": "ABC",
      "Quantity": 123
    },
    {
      "Item": "XYZ",
      "Quantity": 123
    }
  ];

  var portion = arr1.length / 4;
  var ids = [];
  document.querySelectorAll(".best").forEach(e=>   ids.push(e.getAttribute("id")) )
   var counter = -1;
    arr1.map((e,i)=> {
         if(i%portion == 0)
         counter++;
          document.getElementById(ids[counter]).innerHTML += e.Item +","+e.Quantity+"</br>"
    
    } )

 }
<div class="container">
  <div class="best order1" id="one">
    <h1>First List</h1>

  </div>
  <div class="best order2" id="two">
    <h1>Second List </h1>

  </div>
  <div class="best order3" id="three">
    <h1>Third List</h1>

  </div>
  <div class="best order3" id="four">
    <h1>Forth List</h1>

  </div>
  <input type="button" value="List" onclick="myArray();">

</div>

Ps. You'll have to be wise to decide sections based on the number of records you've in your array.

Thanks

Comments

0

const arr1 = [{
  "Item": "Pencil",
  "Quantity": 200
},
{
  "Item": "Rubber",
  "Quantity": 250
},
{
  "Item": "Sharpner",
  "Quantity": 300
},
{
  "Item": "Pen",
  "Quantity": 400
},
{
  "Item": "Paint",
  "Quantity": 500
},
{
  "Item": "Box",
  "Quantity": 50
}];

let listNumber = 1;

const template = arr1.reduce((template, item, index) => {

  if (index % 2 === 0) {
    return template +=
    `<div class="best order1" id="one">
      <h1>List ${listNumber++}</h1>
      ${item.Item}, ${item.Quantity} </br>
    `;
  }

  return  template +=
    `  ${item.Item}, ${item.Quantity}
    </div>`;

}, '')

const resultHTML =
`<div class="container">
  ${template}
</div></br>`;

function list(){
  document.getElementById('content').innerHTML = resultHTML;
}

document.getElementById('btn').onclick = list;
<html>
  <body>
    <div id='content'></div>
    <input type="button" id='btn' value="List">
  </body>
</html>

I would use reduce to create the HTML dynamically:

let listNumber = 1;

const template = arr1.reduce((template, item, index) => {

  if (index % 2 === 0) {
    return template +=
    `<div class="best order1" id="one">
      <h1>List ${listNumber++}</h1>
      ${item.Item}, ${item.Quantity}
    `;
  }

  return template +=
    `  ${item.Item}, ${item.Quantity}
    </div>`;

}, '');

If you don't use es6, you can just concatenate the strings in the old way.

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.