Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return array and function that returns another array together JS

I’m currently trying to return an array with some values and a function that returns another array as well. How do I do it that my returns is basically 2 arrays instead of 1 array and 1 function

Example

const array1 = [a, b, c]

const function = () => {
  if(something) {
    somevalues.map(e => {
      return ( 
        <div>{e}<div>
     )
   })
  } else {
    othervalues.map(f => {
      return ( 
        <div>{f}<div>
     )
   })
  }
} 

return [...array1, function] ??

function in the example obviously returns function instead of its own return, how do I fix that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to

  • actually return something from your function. If you don’t return the return values of somevalues.map(...) and othervalues.map(...) then your function will return undefined.
  • call the function to get its return value
  • spread the return value into the result array, just like you do with the static array.

Example:

const array1 = [a, b, c]

const outerFunction = () => {

  const innerFunction = () => {
    if(something) {
      return somevalues.map(e => (<div>{e}<div>));
//    ^^^^^^
    } else {
      return othervalues.map(f => (<div>{f}<div>));
//    ^^^^^^
    }
  } 

  return [...array1, ...innerFunction()];
//                   ^^^             ^^
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading