How can I map over two arrays at the same time?

15,507

Solution 1

Using the second parameter of map, which is the index of the current element, you can access the correct element of the second array.

const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ];
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]

const players = link.map((value, index) => {
  const linkContent = content[index];
  return (
    <div>
      <Reactplayer url="{value}" />
      <ControlLabel>{linkContent}</ControlLabel>
    </div>
  );
});

This is the perfect candidate for the zip method which is available with various libraries, such as Lodash or Rambda, if you have one of those in your project.

const players = _.zip(link, content).map((value) => {
  return (
    <div>
      <Reactplayer url="{value[0]}" />
      <ControlLabel>{value[1]}</ControlLabel>
    </div>
  );
});

Solution 2

You would be better off having it as:

const data = [
    { link: "www.test0.com", text: "this is test0 content" },
    { link: "www.test1.com", text: "this is test1 content" }
];

You would then render content like:

render() {
    var links = [];
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        links.push(<div><Reactplayer url={item.link}/><ControlLabel>{item.text}</ControlLabel></div>);
    }

    return (<div>{links}</div>);
}

Please note, this is untested code as I don't have a JSX project currently setup that I can test it in.

Share:
15,507

Related videos on Youtube

Deelux
Author by

Deelux

Updated on June 24, 2022

Comments

  • Deelux
    Deelux almost 2 years

    I have two arrays, one with urls and one with content. They look like this:

    const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ]
    const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]
    

    How can I map over both arrays at the same time and use their value in my newly created element?

    I need to use the value of the url for my reactplayer and the the value of the content as the text underneath the player.

    So it should look something like this:

    <Reactplayer url"link0" />
    <ControlLabel>content0</ControlLabel>
    

    Is this possible? And what would be a better way of setting this up?

  • Deelux
    Deelux over 7 years
    I thought already it would be better like that. But I haven't figured out how to be able to save my data in that way. I actually created an other question about this here: stackoverflow.com/questions/41310802/…

Related