Iterating over a loop to display a specific selection of elements from a list

Just starting out with coding and posting for the first time here. I apologize if this question has already been answered, but I'm not sure what exactly to search for anyway...

I'm working on a for loop to render elements from an array pulled from an API. My aim is to display only 10 items based on a specific criteria rather than just the first 10 items in the array.

Here's an example:

for(let i=0;i<json.length;i++)
{
    let product = json[i];
    let category = product.category;
    
    renderProduct(); //this function 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... My goal is to display the first 10 objects that have the category X. I hope this explanation makes sense. Thank you all for your help and input!

Answer №1

To browse through products based on a specific category, you can implement a loop that checks the category and skips to the next iteration if it is not the desired one. You can also use a counter to track the number of relevant products displayed and exit the loop when reaching a specified count.

let displayCount = 8;
for (const item of productArray) {
    if (item.category !== 'Y') continue;
    showProduct(item);
    if (!--displayCount) break;
}

Answer №2

To ensure efficiency, loop through the array to check for specific categories and limit the results to the top ten products:

const items = [{id:1,category:'A'},{id:2,category:'B'},{id:3,category:'C'}...]; // array containing product items
const topProducts = [];
for(let i=0; i<items.length; i++)
{
  let item = items[i];
  let category = item.category;
  if(category === 'A' && topProducts.length <= 9){
    topProducts.push(item);
  }
  if(topProducts.length >= 10){
    break;
  }
}
console.log('Top 10 items in Category A:', topProducts);
renderProduct(); // function to display products on the webpage

Take a look at this example HERE

Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sequelize error: Foreign key mentioned, yet not found in the table

I recently started using Sequelize and have been relying heavily on the documentation available here. The documentation mentions the importance of using hasOne(), hasMany(), and belongsTo() to automatically add foreign key constraints. In my case, I am wor ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Monitoring Selection Updates on Firefox for Android using JavaScript

I am in search of a method to monitor text selections on a webpage. I require code to run every time there is a change in selection. While I have successfully achieved this on the main desktop browsers, I am facing difficulties with Firefox for Android. I ...

Static Arrays or Dynamic Arrays: A Comparison in C++11

Although the debate between static and dynamic arrays has been ongoing for quite some time, I am currently struggling to decide which method to use in a specific case. If I weren't constrained by C++11, I would lean towards using static arrays. Howeve ...

Counting items in AngularJS filters: a step-by-step guide

I have a question regarding my jsfiddle example. Here is the link to my jsfiddle How can I ensure that it counts the number and only displays once instead of repeating multiple times? This is my HTML code: <section class="left" style="border-right:1 ...

Node.js application experiencing bug with End of Line (EOL) not displaying correctly

I've encountered an issue with my node.js application that involves writing the following code: word_meaning = 'line 1' + os.EOL +'line 2'; When attempting to render this in an HTML file using the following code: <p> <% ...

Utilize the `addEventListener` and `removeEventListener` functions on the menu to

Why is my mobile menu not functioning correctly? The submenu should open on the first click and redirect to the parent URL on the second click, which works fine. However, when the window width increases to 768px or more, the submenu should appear on hover ...

Converting a local Node.js server to an online server: A step-by-step guide

Currently working on a game for my school project. Originally designed to be an online multiplayer game, but have only been able to test it locally so far. Need help figuring out how to modify my server code to make it functional as a legitimate online ser ...

Extract the image URL from the href attribute using Xpath

My goal is to extract all images enclosed in href attributes from the given code snippet <div class="jcarousel product-imagethumb-alt" data-jcarousel="true"> <ul> <li> <a href="https://domain/imagefull.jpg" onclick="return false;" cla ...

Adaptable design tailored for smartphones

When it comes to developing mobile websites for various platforms such as iPhone 3 and 4, Android, Blackberry Torch, etc., I usually find myself needing to slice images based on the specific platform. The challenge arises from constantly having to slice im ...

Three.js: transforming textures into data textures

Currently, my goal is to create a delayed webcam viewer using javascript, utilizing Three.js for its WebGL capabilities. At the moment, I am able to capture frames from the webcam and display them after a specified time interval using canvas and getImageD ...

PHP - Store an implementation of an interface within an array

Having trouble finding the answer online, I'm not quite sure how php and interfaces work. The issue is with the if(!variable instanceof class) statement. The checked class is actually an interface and needs to be in an array, as shown in the followin ...

Using React to organize and showcase text messages in categorized sections

I am looking to organize text messages into different sections based on when they were received: This includes messages received today, yesterday, this week, this month, and continuing in month intervals as needed... For example: https://i.sstatic.net/R ...

Extracting precise information from a JSON file using Angular's $http.get

I am struggling with extracting a specific user from a JSON file containing a user list and displaying it on an Angular index page. Despite extensive research, I have been unable to find a satisfactory solution. The user list must remain in a JSON file ins ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

How do I specify filter selectors for events passed as an object in JQuery's on() method?

I've been pondering about the second syntax of JQuery's on() method where events are passed as an object: services.on({ 'mouseenter': function(e){ console.log('enter', e.target); }, 'mouseleave': function ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

Top recommendation: Efficiently displaying voxel-based data using WebGL

I am in search of the most effective practice or practices for solving the following problem. I will strive to describe it in a way that is abstract enough to be applied to unforeseen scenarios. Available data consists of Voxels (volumetric pixels) formin ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...