Home > Blockchain >  Cleaner/Simpler way to check if content in array has a value greater than 0
Cleaner/Simpler way to check if content in array has a value greater than 0

Time:12-24

I have this array that combines different data and then if the array contains true, then I'm showing some text. So for example, even if video is the only one that has a length greater than 0 (true), and the rest are false, the text 'Click to go to list' will be still shown. Is there a clean/simplier way of doing this check?

const relatedLists = [
 videos.length > 0, // returns true or false
 interviews.length > 0,
 pdf.length > 0,
 audio.length > 0,
 book.length > 0,
];

Link={
 relatedList.includes(true) ? 'Click to go to list' : ''
}

CodePudding user response:

You can check to see if atleast one length property in the array is truthy

Link={relatedList.some(v => !!v.length) ? 'Click to go to list' : ''}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Some

  • Related