Home > Blockchain >  How could I limit the amount of items in an array (js)
How could I limit the amount of items in an array (js)

Time:01-25

let items = querySnapshot.docs.map(post => {
  if(xy < 20){
return `<div id="postBox">
  <h4 id="postName">${post.data().display_name}</h4>
  <h1 id="postTitle">${post.data().title}</h1>
  <h3 id="postDescription">${post.data().description}</h3>
  <h5 id="postId">post id:${post.id}<h5>
      <h6 id="postUid">uid:${post.data().uid}<h6>
  <div id="likeContainer"><ion-icon name="thumbs-up-outline" id="likeBtn"></ion-icon><h3 id="likeCount">${post.data().likes}</h3></div>
  </div>`
  xy = xy   1;
}
});

I would like to make it so the array has 20 items.

I have tried lots of different ways to do this and none of them have worked so now I am gonna get downvoted out of existence.

CodePudding user response:

Take only a max of 20 items, then do the map. If there are more than 20 items, it will max out at 20, if there are less it won't insert empty items.

let items = querySnapshot.docs.slice(0, 20).map(post => {
  return `<div id="postBox">
    <h4 id="postName">${post.data().display_name}</h4>
    <h1 id="postTitle">${post.data().title}</h1>
    <h3 id="postDescription">${post.data().description}</h3>
    <h5 id="postId">post id:${post.id}<h5>
    <h6 id="postUid">uid:${post.data().uid}<h6>
    <div id="likeContainer"><ion-icon name="thumbs-up-outline" id="likeBtn"></ion-icon><h3 id="likeCount">${post.data().likes}</h3></div>
  </div>`;
});

const data1 = [1, 2, 3, 4];

console.log(data1.slice(0, 20).map(n => `number ${n}`));

const data2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25];

console.log(data2.slice(0, 20).map(n => `number ${n}`));

  • Related