Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping from two different data sources

I have a React functional component with the following JSX:

import React from "react";

const Parent = () => {
  const arr1 = ["123", "456"];
  const arr2 = ["abc", "def"];

  return (
    <div>
      {arr1.map((item) => {
        return <div>{item}</div>;
      })}
      {arr2.map((item) => {
        return <div>{item}</div>;
      })}
    </div>
  );
};

export default Parent;

What I need this component to render is:

"123"
"abc"
"456"
"def"

Instead, it returns:

"123"
"456"
"abc"
"def"

I tried to get the result with a for loop, but for some reason it doesn't get triggered when the functional component is loaded, so I'm looking for a solution that involves .map(). Is there a way to get the needed result with .map()?

Note: the lengths of arrays are always equal, hence the accepted answer.

like image 580
Ruham Avatar asked Nov 28 '25 02:11

Ruham


2 Answers

Assuming that both array have the same length:

<div>
  {arr1.map((item, index) => (<>
    <div>{item}</div>
    <div>{arr2[index]}</div>
   </>);
  )}
</div>
like image 69
lissettdm Avatar answered Nov 30 '25 17:11

lissettdm


return (
  <div>
    {arr1.map((value, index) => {
       return <> <div>{value}</div> <div>{arr2[index]}</div> </>
    })}
  </div>
);
like image 20
Majed Badawi Avatar answered Nov 30 '25 15:11

Majed Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!