How to break a map() loop in React

How to break a map() loop in React

This article will show you the answers to the question: How to break a map() loop in React? For example, using the Array.slice() or the Array.reduce() method. Let’s go into detail now.

Break a map() loop in React

Look at the code below, we have an array of users consisting of three users that are mapped and rendered to the screen.

Code:

import React from 'react';
const App = () => {
  const users=[
    {
      id:1,
      name:"Han",
      email:"[email protected]",
    },
    {
      id:2,
      name:"Tommy",
      email:"[email protected]",
    },
    {
    id:3,
    name:"Jimmy",
    email:"[email protected]",
  },
]
 
  return (
    <div className="container">
        <h2>How to break a map() loop in React | LearnShareIT</h2>
        <hr/>
       
        <ul>
           {users.map((user)=>{
            return(
              <li>{JSON.stringify(user)}</li>
            )
           })}
        </ul>
    </div>
  );
};
 
export default App;

Output:

For example, we only need to map out the first two parts of the Array. How do we break map() when we need to map out more elements? Let’s see how to do it here.

Using Array.slice() method

The slice() method is used to get (extract) part of an array.

Syntax:

array.slice(start, end);

Parameters:

  • start is the index of the element you want to start getting.
  • end is the index of the element you want to end (don’t get).

In this way, we will use the Array.slice() method with the user’s Array defined before mapping it.

Code:

import React from 'react';
 
const App = () => {
  const users=[
    {
      id:1,
      name:"Han",
      email:"[email protected]",
    },
    {
      id:2,
      name:"Tommy",
      email:"[email protected]",
    },
    {
    id:3,
    name:"Jimmy",
    email:"[email protected]",
  },
]
 
  return (
    <div className="container">
        <h2>How to break a map() loop in React | LearnShareIT</h2>
        <hr/>
        <ul>
           {users.slice(0,2).map((user)=>{
            return(
              <li>{JSON.stringify(user)}</li>
            )
           })}
        </ul>
    </div>
  );
};
 
export default App;

Output:

When you use slice() on the Array before you map it, you can control the length of the Array, and it can also be considered a kind of breaking map.

Using Array.reduce() method

Reduce is a built-in method used to execute a function on the elements of an array (from left to right) with an accumulator to obtain a single value.

Syntax:

arr.reduce(callback( accumulator, currentValue[, index[, array]] ) {
  // return result 
}[, initialValue])

Parameters:

  • accumulator variable returned after each callback function call.
  • currentValue element of the Array being processed.
  • index (Optional): The index of the element in the Array being processed.
  • array (Optional): The current Array calls the reduce() function.

In this way, we will use the Array.reduce() method to return us the values ​​of the Array whose index is less than two.

Code:

import React from 'react';
const App = () => {
  const users=[
    {
      id:1,
      name:"Han",
      email:"[email protected]",
    },
    {
      id:2,
      name:"Tommy",
      email:"[email protected]",
    },
    {
    id:3,
    name:"Jimmy",
    email:"[email protected]",
  },
]
 
  return (
    <div className="container">
        <h2>How to break a map() loop in React | LearnShareIT</h2>
        <hr/>
        <ul>
           {users.reduce((result, current, i) => {
             if (i < 2) {
               result.push(
               <li>{JSON.stringify(current)}</li>
               );
             }
               return result;
             }, [])}
        </ul>
    </div>
  );
};
 
export default App;

When you use this reduce method, we will run through a callback to check the index of the element. If it less than two, it will return the li tag. Otherwise, the program stops and the return result is the same as the previous method first. Wish you success with the methods we provide.

Summary

We have shown you how to break a map() loop in React in two ways. However, we recommend you use the slice() method because it’s easier. Good lucks for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *