Skip to content Skip to sidebar Skip to footer

How Can I Map Over Two Arrays At The Same Time?

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 con

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><Reactplayerurl="{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><Reactplayerurl="{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><Reactplayerurl={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.

Post a Comment for "How Can I Map Over Two Arrays At The Same Time?"