-1

new to coding and first time poster here. i apoligze if this has been answered before, but i'm not exactly sure what i would look up to find it anyhow..

i'm going through a for loop rendering elements of an array that's pulled from an api. my goal is to only print 10 items from that array based on element of that array (i.e. not the first 10 items of the array but the first 10 items of the array that meet a criteria)

something like this:

for(let i=0;i<json.length;i++)
{
  let product = json[i]
  let category = product.category
  
  renderProduct() //this is a function that prints the product to the DOM
 }

in my api, each object has a category, let's say some are X, some are Y, some are Z, some are Q, etc....I want to be able to print the first 10 that are X - hoping this makes sense, and thank you all for your help and input!

bmceuen
  • 21
  • 2
  • 1
    Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – 0stone0 Mar 22 '21 at 14:20
  • Searching internet is one of the most useful skills you can have as a programmer. – Ula Mar 22 '21 at 14:36

2 Answers2

0

You could iterate with a check for the category and continuethe loop if not wanted and use a counter to count wanted product until zero and exit the loop.

let count = 10;
for (const product of json) {
    if (product.category !== 'X') continue;
    renderProduct(product);
    if (!--count) break;
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You need to use check inside your array and execute renderProduct() function outside the loop:

var json = [{id:1,category:'X'},{id:2,category:'X'},{id:3,category:'Y'}...]; // this array contain list of your items
var topTen = [];
for(let i=0;i<json.length;i++)
{
  let product = json[i]
  let category = product.category
  if(category == 'X' && topTen.length <= 9){
    topTen.push(product);
  }
  if(topTen.length >= 10){
    break;
  }
}  
console.log('first 10 items by category: ', topTen);
renderProduct() //this is a function that prints the product to the DOM

Check this example HERE

Good luck