I have a list of dicts ‘players’:
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Each dict with the following structure:
{name:'John', position:'fwd'}, {name:'Peter', position:'mid'}, {name:'Bill', position:'def'},...
And I’m extracting an displaying one player name per row, like so:
render() { const { players } = this.props; if(players){ return ( <div className="app"> <div className="pos-wrapper"> <div className="row"> <Row>{players[0].name}</Row> <Row>{players[1].name}</Row> <Row>{players[2].name}</Row> </div> <div className="row"> <Row{players[3].name}</Row> <Row>{players[4].name}</Row> <Row>{players[5].name}</Row> </div> <div className="row"> <Row>{players[6].name}</Row> <Row>{players[7].name}</Row> <Row>{players[8].name}</Row> </div> </div> </div> </div> ); }else{ return null} }
Now I need to display only forwards on the first 3 <Row>
components, mids on the second group, and defenders on the last group of <Row>
.
QUESTION:
How do I create a function in javascript that takes ‘position’ as an argument and display the first, second and third name for each player, and call this function like so?
<Row>call here</Row> <Row>call here</Row> <Row>call here</Row>
Note: I cannot use map()
, I must keep the layout structure above.
Advertisement
Answer
If I understand this correctly, you want to group them by positions, right?
In this case, you can create a function then filter()
the array depending on the player’s position then map()
them. To make sure it’s just the first 3, then maybe you can also use slice()
This shouldn’t change the original array.
function getPlayersByPosition(players, position){ return players.filter((player) => player.position === position).slice(0, 3); } const players = [{name: "One", position: "fwd"}, {name: "Two", position: "db"}, {name: "Three", position: "fwd"}]; // React code now getPlayersByPosition(players, "fwd").map((player) => <Row>{player.name}</Row>)
You can use it this way.
<div className="row"> {getPlayersByPosition(players, "fwd").map((player) => ( <Row>{player.name} </Row> ))} </div>
Hopefully this answers your question or at least points you to the right direction!