ReactJS how to map an array based on the order of another array

 order: [ "567", "645", "852", "645", "852", "852", ]

database: [ { "userId": 567, "userName": "tjk23", "department": "Sales", "remarks": "" }, { "userId": 645, "userName": "gfn23", "department": "Sales", "remarks": "" }, { "userId": 852, "userName": "dan24", "department": "Sales", "remarks": "", } ]

Currently it's mapping fine with the database array, but only displays 3 of the DisplayCard. I need it to display 6 times and also in the order of the 6 in order array

{database.map((data, index) => { return <DisplayCard data={data} key={index}/> })}

How do I make it map using the sequence of the order array without changing too much code? As the DisplayCard is used in multiple places I would like to not modify it

I tried using

{order.map((database.data, index) => { return <DisplayCard data={database.data} key={index}/> })}

and expected it to use the sequence of the order array, and get the data from the corresponding userId in the database array

But what actually resulted is an error but I don't know why


You can achieve the desired behavior by using the map() function on the order array and for each element, finding the corresponding element in the database array using the userId property. Here's an example code snippet that should work for your scenario:

javascript
{order.map((userId, index) => { const data = database.find(d => d.userId === userId); return <DisplayCard data={data} key={index}/> })}

In this code snippet, we're using the map() function on the order array and for each element (which is a userId), we're using the find() function on the database array to find the corresponding element based on the userId property. The resulting element is then passed to the DisplayCard component as a prop.

Note that the find() function returns the first element in the database array that satisfies the provided testing function. If there are multiple elements with the same userId, it will return the first one it finds. If you need to handle this case differently, you can modify the code accordingly.

Comments