1

I have a function that produces two 2d arrays; how do I return both of them?

I can return two 1d arrays

function test() {
  do some stuff and get
  arr1 =["A',"B","C"]
  
  do some other stuff and get
  arr2 =["X","Y","Z"]


  return [arr1,arr2]
}

test[0]= arr1

test[1]=arr2

But if I have

function test() {
  do some stuff and get
  ary1 =[
         ["A',"B","C"],
         ["M',"N","O"]
        ] 
         

  do some other stuff and get
  ary2 =[
         ["X","Y","Z"],
         ["M',"N","O"]
        ] 
  return [ary1,ary2]
}

and I get

test[0] =["A',"B","C"]

test[1] =["X","Y","Z"]

Expected result:

test[0] =[
          ["A',"B","C"],
          ["M',"N","O"]
         ]

test[1] =[
          ["X","Y","Z"],
          ["M',"N","O"]
         ] 

how do I return ary1 and ary2?
4
  • I have to apologize for my poor English skill. Unfortunately, from your question, I cannot understand your expected values. So, when the values of ary1 and ary2 of your 2nd script are used, what are your expected values? Commented Feb 7, 2023 at 3:19
  • What is the expected result? Commented Feb 7, 2023 at 3:19
  • Sorry, I update my question Commented Feb 7, 2023 at 3:22
  • Thank you for replying. Although unfortunately, I'm not sure whether I could correctly understand your question, I posted an answer. Please confirm it. If I misunderstood your question, I apologize. Commented Feb 7, 2023 at 3:25

1 Answer 1

1

I think that in your script, test of test[0] and test[1] is the function. So, in this case, please modify test()[0] and test()[1].

function test() {
  ary1 = [["A", "B", "C"], ["M", "N", "O"]];
  ary2 = [["X", "Y", "Z"], ["M", "N", "O"]];
  return [ary1, ary2];
}

console.log(test()[0]);
console.log(test()[1]);

Note:

  • As additional information, in the case of test()[0] and test()[1], the script of test() is run 2 times. So, in this case, I thought that the following sample might be suitable.

function test() {
  ary1 = [["A", "B", "C"], ["M", "N", "O"]];
  ary2 = [["X", "Y", "Z"], ["M", "N", "O"]];
  return [ary1, ary2];
}

const values = test();
console.log(values[0]);
console.log(values[1]);

// or the following sample can be also used.
const [a, b] = test();
console.log(a);
console.log(b);

Sign up to request clarification or add additional context in comments.

1 Comment

I swear I tried that initially, and it did not work!! But now it does. Thank you for your kind reply

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.