Search code examples
javascriptarraysreactjscomparelodash

How can we compare two array of objects and display items from both array


I have two arrays like

 const arr1=[{id:0,name:'aa', 
  userId:'22,23'}, 
  
 {id:1,name:'bb',userId:'23'}]
 const arr2= 
 [{id:22,username:'Peter'},
  {id:23,username:'John'}]

 arr1.map((val,k)=><div>
     <p>val.userId</p>
 </div>

I have getting output as

    22,23
    23

How to get an output like

   Peter,John
   John

Solution

  • You can use find() to get the username from arr2

    const arr1 = [
      { id: 0, name: "aa", userId: "22,23" },
      { id: 1, name: "bb", userId: "23" },
    ];
    const arr2 = [
      { id: 22, username: "Peter" },
      { id: 23, username: "John" },
    ];
    
    const output = arr1.map(o =>
      o.userId
        .split(",")
        .map(x => arr2.find(k => k.id === Number(x)).username)
        .join(",")
    );
    
    output.map((val)=> <div><p>val</p></div>);