sando xavier
sando xavier

Reputation: 35

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

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.

Upvotes: 1

Views: 95

Answers (1)

Samathingamajig
Samathingamajig

Reputation: 13283

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}`));

Upvotes: 4

Related Questions