Home > Software design >  Break map loop inside return in component
Break map loop inside return in component

Time:01-11

I'm trying to loop into an array to create the component content, if condition on array element is not satisfied then break the loop and return 1 component

leaves.map(leave => leave.id === currentUser.id ? <div> {leave} </div> : <div> no leaves </div>)

This is the code I have so far, no leaves is printed out every time leave.id is different than currentUser's id

What I need to is, print no leaves only when none of the leaves's id matches the currentUser's id and therefore I want to break the map after printing no leaves

CodePudding user response:

You should use Array.prototype.some. In your case, you would pass a function to the method to check whether it satisfies your condition and use the ternary operator to render the content.

const arrWithId = [670760658, 250026214, 126834449, 987103760, 882536150, 666896331, 488576796, 186598055, 103751309, 419995457, 503676712, 487691896, 744253979, 269253696, 102370148, 237328910, 409016979, 979651614, 743486466, 445993562, 779323321, 939834768, 296731253, 925812473, 114149678];
const arrWithoutId = [123456789, 250026214, 126834449, 987103760, 882536150, 666896331, 488576796, 186598055, 103751309, 419995457, 503676712, 487691896, 744253979, 269253696, 102370148, 237328910, 409016979, 979651614, 743486466, 445993562, 779323321, 939834768, 296731253, 925812473, 114149678];
const id = 123456789;

const checker = elem => id === elem;
console.log(`With ID: ${arrWithId.some(checker) ? "yes" : "no"}`)
console.log(`Array: ${arrWithId}`);
console.log(`Without ID: ${arrWithoutId.some(checker) ? "yes" : "no"}`)
console.log(`Array: ${arrWithoutId}`);

  •  Tags:  
  • Related