How to break .map function How to break .map function reactjs reactjs

How to break .map function


Use Array.slice before you map.

peopleGroup.slice(0, 5) // creates a copy of original, 5 items long.map(...) // subsequent operations work on the copy

Tada!


How to break a .map function?

Not possible, We can't break #array.map, it will run for each element of array.

To solve your problem, you can use slice first then map, slice first 5 elements of array then run map on that.

Like this:

peopleGroup.slice(0,5).map((people, i) => {    return (...)}


instead of using .slice and .map which will create another loop.
You can use .reduce, that way you are doing your logic with one loop (better performance).
The difference is that .map will have to return the same length of the array, where .reduce can return anything actually.

  data.reduce((result, current, i) => {    if (i < 5) {      result.push(<div>{current}</div>);    }    return result;  }, [])

Running example:

const data = [1, 2, 3, 4, 5, 6, 7];const App = () => (  <div>    {data.reduce((result, current, i) => {      if (i < 5) {        result.push(<div>{current}</div>);      }      return result;    }, [])}  </div>);ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>