1

I have the below array of objects named getRecommendations. I will be using this to map the data which i will be receiving from backend.

const getRecommendations = [
 { 
  recoTitle: "Retire",
  recoDescription: "Its time to retire and relax with family"
 },
 {
  recoTitle: "Buy home",
  recoDescription: "Start saving to buy home in near future"
 }
]

Below is the array of recommendations i receive from backend and it is in sequence of ranks. for e.g. Buy home is rank 1 and Retire is rank 2 in this case. sometimes it may be other way around. I want to display the recommendations in the same order as i receive from the backend to the UI display.

const recommendations = ["Buy home", "Retire"];

But i do the following mapping because i not only need recoTitle but also recoDescription to display the user. I have getRecommendations which does a mapping of recoTitle and recoDescription. The below code is used to get both in the array of object. It is as follows

const filteredReco = getRecommendations.filter(
  ({ recoTitle}) => recoDetails && recoDetails.indexOf(recoTitle) !== -1,
);

now, if i see the contents of filteredReco by using console log, Retire will come as a first object and then Buy Home. How can i ensure the order of listing is not affected by the way i use filter. Can someone please suggest.

4
  • This is because you are iterating the getRecommendations, and the sequence is based on that. If you want to maintain the order in recommendations, you need to rewrite the logic to loop throuh each item in recommendation array and fetch the matching obj from getRecommendations Commented Nov 10, 2020 at 6:02
  • recommendations.map(recName => getRecommendations.find(rec => rec.recoTitle === recName)) something like this? Commented Nov 10, 2020 at 6:13
  • @igk- Yes, this worked. thanks. Can you post it as an answer too. Might help someone Commented Nov 10, 2020 at 6:18
  • yes, ofcourse. Happy coding! Commented Nov 10, 2020 at 6:23

1 Answer 1

1
recommendations.map(recName =>  
   getRecommendations.find(rec => rec.recoTitle === recName)
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.