kerim Erkan
kerim Erkan

Reputation: 171

Custome Mapping in React Native

I have an array state that I am trying to map into a component where every third item goes into a prop. the array contains the following:

players: [1, "Timmy", "H", 2, "Julie", "M"]

Here is how I am mapping it:

const myPlayers = this.state.players.map((id, first, last) =>
        <Player 
            key={id} 
            fName={first} 
            lName={last} 
        />
    )

basically, the 0,3,6,9... items of the array are indexes the 1,4,7,10... items of the array are the first name the 2,5,8,11... items of the array are the last name

When I try to map it into the component as mentioned in the code snippet above, I get this result on my screen:

0 1TimmyH2JulieM
1 1TimmyH2JulieM
2 1TimmyH2JulieM
3 1TimmyH2JulieM
4 1TimmyH2JulieM
5 1TimmyH2JulieM

The result I am hoping to get is:

Timmy H
Julie M

Here is the code snippet of my Player Component for reference:

<TouchableOpacity>
        <View style={styles.container}>
        <Text style={styles.name}>{props.fName} {props.lName}</Text>
        </View>
</TouchableOpacity>

Any idea how to achieve this? Thanks

Upvotes: 0

Views: 31

Answers (1)

Cristian Riță
Cristian Riță

Reputation: 559

This is not how map works. Map applies the function to every element of the array. You cannot group them. What I suggest you to do is to have a structure like this: players: [{id:1, firstName:"Timmy", lastName:"H"}, {id:2, firstName:"Julie", lastName:"M"}]. This way your map will work, plus is much easier to deal with operations like push or remove and other programmer can easily understand your code.

If you still want to keep that structure you should use a for instead of map.

Upvotes: 1

Related Questions