Skip to content

Get values from dictionary based on condition and display results

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;
    return (
     <div className="app">
        <div className="pos-wrapper">
          <div className="row">
          <div className="row">
            <div className="row">
    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>.


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.


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>{}</Row>)

You can use it this way.

<div className="row">
   {getPlayersByPosition(players, "fwd").map((player) => (
        <Row>{} </Row>

Hopefully this answers your question or at least points you to the right direction!