Ways to showcase only five items of data using the map method

I'm working on a project that involves displaying data from an external Json file on my site. However, I'm facing an issue where I need to limit the display to only 5 items.

const displayCharacters = (characters) => {
                characters.sort((a, b) => {
                    return a.rate - b.rate;
                });
                characters.sort((a, b) => b.rate - a.rate);

                characters.forEach(() => {
                    const htmlString = characters
                        .map((character) => {
                            return `
                                <div class="col-6 my-2" onClick="addToCart(${character.id})"></div>
                                    <div class="menu card my-3" style="width: 120px">
                                        <div class="card-body">
                                            <h5 class="menu-name">${character.nama}</h5>
                                            <p> ${character.harga}</p>
                                        </div>
                                    </div>
                                    </div>
                            `;
                        })
                        .join('');
                    charactersList.innerHTML = htmlString;
                });
            };

            loadCharacters();

If anyone could offer assistance, it would be greatly appreciated.

Answer №1

If you want to manipulate an array in JavaScript, you can utilize the slice method before applying the map function for desired results.

    const showItems = (items) => {
          items.sort((x, y) => {
            return x.value - y.value;
          });
          items.sort((x, y) => y.value - x.value);
        
          items.forEach(() => {
            const itemHTML = items
              .slice(0, 5)
              .map((item) => {
                return `
                          <div class="col-6 my-2" onClick="addToBasket(${item.id} )"></div>
                            <div class="product card my-3" style="width: 120px">
                              <div class="card-body">
                                <h5 class="product-name">${item.name}</h5>
                                <p> ${item.price}</p>
                              </div>
                            </div>
                          </div>
                  `;
              })
              .join('') ;
            itemList.innerHTML = itemHTML;
          });
        };
        
        loadItems();

Answer №3

You can iterate through the index in a foreach loop and check if the index is less than or equal to 5

        const displayCharacters = (characters) => {
                          // Sorting characters based on rate in ascending order
                          characters.sort((a, b) => a.rate - b.rate);
                          // Sorting characters based on rate in descending order
                          characters.sort((a, b) => b.rate - a.rate);
                        
                          characters.forEach(funtion(data,index) { //Using index value to set data limit 
                            const htmlString = characters
                              .map((character) => {
                            if(index=<5){ //Checking if index is less than or equal to 5
                                return `
                                          <div class="col-6 my-2" onClick="addToCart(${data.id} )">
                                            <div class="menu card my-3" style="width: 120px">
                                              <div class="card-body">
                                                <h5 class="menu-name">${data.nama}</h5>
                                                <p> ${data.harga}</p>
                                              </div>
                                            </div>
                                          </div>
                                  `;
 }
                              })
                              .join('') ;
                            charactersList.innerHTML = htmlString;
    
                          });
           
                        };
                        
                        loadCharacters();

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

The issue of infinite scroll functionality not functioning properly when using both Will Paginate and Masonry

I'm having trouble getting the Infinite Scroll feature to work on my website. I've successfully implemented Masonry and Will Paginate, but for some reason, the Infinite Scroll isn't functioning as expected. I suspect that the issue lies wit ...

JSP - Submitting a form through a link click: A complete guide

I am having an issue with submitting a form when clicking on a link. Despite my attempts, the default action is not being prevented and I keep getting the error message: HTTP Status 405 - Request method 'POST' not supported. Here's what I ha ...

Wavy CSS Animation

For assistance with my spinning image, please check out this fiddle: https://jsfiddle.net/dricardo1/9a8p6srb/ Hello! I'm struggling with a spinning image that has a noticeable wobble when rotating. I can't seem to find a solution to make the rot ...

Updating the object does not result in the interpolation value being updated as well

I am facing an issue with this v-for loop: <tr v-for="(product, index) in products" v-bind:key="products.id"> <div v-on:click="decrementQtd(index)" class="action-qtd-button-left"> <strong>-</strong> </div> < ...

Show a pop-up notification when the mouse passes over a word in the text

I've been grappling with this issue for days now and could really use some guidance. Despite scouring the web, I'm unsure if I've approached it correctly. What I'm trying to achieve is having an alert box pop up each time a user hovers ...

What methods can I use to obtain negative numbers through swipe detection?

In my code, I am using three variables. The first one is x which serves as the starting point, followed by myCount which counts the number of swipes a user performs, and finally, dist which calculates the distance from the initial point. I want to set myC ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Encountering a 500 error within a Passport JS and React application

I'm currently developing a chat application using React, and I've hit a roadblock while trying to authenticate users. The axios post request is throwing a 500 error that seems to be elusive. Even when the correct credentials are entered for a use ...

`How can textures be added to the front and back of a shape in Three.js geometry?`

I'm currently working on creating a flat shape geometry with rounded corners. Below is a snippet of the code I have so far: var geometry = new THREE.ShapeGeometry(shape); var front_material = new THREE.MeshPhongMaterial({ map: frontTexture, s ...

Is there a way to implement a timeout for redirection or new pages opened on a different server?

Is there a way to redirect my page to another website, like google.com, or to open google.com as an additional page in the browser? In addition, is there a way to close any previously opened google pages (if opened as a new page) or return to my page (if ...

Why is receiving input value in React not successful?

Attempted to retrieve input value when user clicks search, but encountered difficulties. var Login = React.createClass({ getInitialState: function () { return {name: ''}; }, handleSearch(){ alert(this.state.name); // Why isn't ...

The React page is stuck in a perpetual cycle of reloading every single second

After developing an invoice dashboard system using React, I encountered a recurring issue with a similar version of the app built on React. Even after commenting out all API calls, the useEffect(), the page kept reloading every second. Any advice or sugge ...

What is the method to detect the presence of any value from one array in another array using AngularJS?

In my AngularJS factory method, I am creating a permission function to check the user's role. If the user object contains the specified role, the result should be true; otherwise, it should return false. Here is an example of my user object: administ ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

Sorting DataGridView columns based on matching strings

I am trying to implement a feature in my datagridview where the rows are sorted based on a user-entered search string. The search string is compared with the strings in a specific column, and the rows are sorted in descending order based on the matching cr ...

Building React applications with server-side rendering using custom HTML structures

I recently started using Suspense in my React app and decided to implement SSR. However, as I was going through the documentation at https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream, I couldn't find a clear explanation on how to u ...

Utilizing Jquery to retrieve an array as the return value from a $.post request

After going through numerous discussions on this topic, I'm still struggling to make it work. However, I've made significant progress. I have a scenario where I send data from jQuery to my database. The database returns a record consisting of two ...

Establish a timeout for the Material UI drawer to close automatically after being opened

I am looking for a way to automatically close the drawer after a specific duration, but it seems that material UI drawer does not have the necessary props for this. Is there a workaround using transitionDuration or perhaps adding a setTimeout in my functio ...

How to generate a JSON object in a Bash script by capturing the output of a command

As I delve into a shell script, my primary goal is to dynamically transform the output of a command into a JSON object. The structure of the output seems favorable, formatted as "key":"value". In theory, this should be straightforward, right? However, afte ...

Maximizing code reusability in Javascript and React: A guide to avoiding repetition

While creating a back button feature for query processing, I found myself constantly using if statements to handle additional queries in the URL. Unfortunately, the '(([query, value]' format is necessary and requires an extra if statement each ti ...