How to break .map function

how to break .map function? Sample code is attached below. I want to change the look as soon as the index reaches 5, because I only want to display 5 avatars on the screen.

<View style={{ flexDirection: 'row', marginTop: 20, marginLeft: 30  }}>
    {
      peopleGroup.map((people, i) => {
        if(i<5) {
          return (
            <Avatar
              key={people.id}
              width={30}
              position='absolute'
              containerStyle={{ transform: [{translate: [-28 + (28 * i), 0, 1 - (i * 0.1)]}] }}
              small
              rounded
              source={{uri: people.image}}
              activeOpacity={0.7}
              />
          )
        }else if(i===5) {
          return (
          <View key={i} style={{ transform: [{translate: [(25 * i), 9, 0]}]  }}>
            <Text>{peopleGroup.length}</Text>
          </View>
          )
        }
      }
      )
    }
</View>
+4
source share
3 answers

Use Array.slicebefore display.

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

TA-dah!

+6
source

instead of .sliceand .map, which will create another loop.
You can use .reduceit this way, you do your logic with a single loop (better performance).
The difference is that you .maphave to return the same length of the array where you .reducecan return something.

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

Execution 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>
Run codeHide result
+2
source

.map?

, # array.map, .

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

Like this:

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

Source: https://habr.com/ru/post/1692158/


All Articles