is there a faster way to display every index of an array

Viewed 75

im creating a function that will create a p element for every item in an array

  const liArray = ["hello", "hi", "hello", "test", "hey"];

  const parentElement= document.getElementById("myDiv");
  const index1 = liArray.slice(-1);
  const p = document.createElement("p");
  p.innerHTML = "1. " + index1;
  parentElement.appendChild(p);
  
  const index2 = liArray.slice(-2, -1);
  const p2 = document.createElement("p");
  p2.innerHTML =  "2. " + index2;
  parentElement.appendChild(p2);
  
  const index3 = liArray.slice(-3, -2);
  const p3 = document.createElement("p");
  p3.innerHTML =  "3. " + index3;
  parentElement.appendChild(p3);
   
  const index4 = liArray.slice(-4, -3);
  const p4 = document.createElement("p");
  p4.innerHTML =  "4. " + index4;
  parentElement.appendChild(p4);
 
  const index5 = liArray.slice(-5, -4);
  const p5 = document.createElement("p");
  p5.innerHTML =  "5. " + index5;
  parentElement.appendChild(p5);

so the result of this will be

1. hello
2. hi
3. hello
4. test
5. hey

and im wondering if there is any faster way to do it instead of manually slicing the array and creating elements like that which takes a lot of time especially if there is many items in the array

3 Answers

Use Array.prototype.forEach() to loop through each element of the array.

Try this

const liArray = ["hello", "hi", "hello", "test", "hey"];

const parentElement = document.getElementById("myDiv");

liArray.forEach((currentValue, index) => {
  var elm = document.createElement('p');
  elm.innerHTML = `${index + 1}. ${currentValue}`;
  parentElement.appendChild(elm);
});
<div id="myDiv"></div>

You can also use DocumentFragment. Loop over the array and append the newly created p element to the fragment.

When appending a series of elements to the DOM, DocumentFragment is preferred.

const liArray = ["hello", "hi", "hello", "test", "hey"];

var fragment = new DocumentFragment()
const parentEl = document.getElementById("parent");

liArray.forEach(function(currentValue, index){
  var elm = document.createElement('p');
  elm.innerHTML = `${index + 1}. ${currentValue}`;
  fragment.appendChild(elm);
});

parentEl.appendChild(fragment)
<div id="parent"></div>

Related