0

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?

15
  • 1
    I'm confused. You say you are trying to return an array and a function and then you are saying you want to return two arrays instead of an array and a function? What is it now? "function in the example obviously returns function instead of its own return, how do I fix that?" Call the function? Commented Mar 2, 2022 at 12:11
  • Change function into a valid variable like X Commented Mar 2, 2022 at 12:11
  • Rename function into something like func and in returned array use func() instead of func Commented Mar 2, 2022 at 12:13
  • @FelixKling I'm trying to return only values of the function so I end up in the result with array of variables from array1 and variables that the function return Commented Mar 2, 2022 at 12:13
  • @EzioMercer that returns undefined Commented Mar 2, 2022 at 12:14

2 Answers 2

1

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()];
//                   ^^^             ^^
}
Sign up to request clarification or add additional context in comments.

Comments

0
const array1 = ['a', 'b', 'c'];
const something = true;

const func = () => {
  if(something) {
    return 'e';
  } else {
    return 'f';
  }
};

console.log([...array1, func()]); //[ "a", "b", "c", "e" ]

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.