0

How can I return the values of an array? The methods .values() and .entries() seem to return an Array Iterator. This is not what I want. I am also not allowed to modify func1() function for this edge case.

const test = func1();

console.log(test); // actual: [[1,2]] what I want: [1,2]

function func1() { // not allowed to modify func1
  return [func2()];
}

function func2() {
  const set = new Set();
  set.add(1);
  set.add(2);
  return Array.from(set); 
  // return Array.from(set).values() returns Array Iterator
}

Thanks!

4
  • 1
    What's the problem with using const test = func1()[0]? Commented May 1, 2021 at 11:30
  • You could flatten the result with func1().flat();. Commented May 1, 2021 at 11:31
  • in my use case the return value from func2 is not always an array. therefore, I want to see if its possible to just return the values. Commented May 1, 2021 at 11:32
  • But func1 always returns an array, so it doesn't matter what func2 returns. Commented May 1, 2021 at 11:36

2 Answers 2

1

As Bergi stated, func1() will always return an array, no matter what func2() returns. But there are a couple of ways to achieve this based on the return value of func1().

You can either simply use the first element in the array test[0], you can use the Array.flat() method, or the spread operator. See the snippet below.

const test = func1();

function func1() { // not allowed to modify func1
  return [func2()];
}

function func2() {
  const set = new Set();
  set.add(1);
  set.add(2);
  return Array.from(set); 
  // return Array.from(set).values() returns Array Iterator
}

// First element in array
console.log(test[0]);

// Array.flat()
console.log(test.flat());

// Spread operator
console.log(...test);

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

3 Comments

When the OP writes "I am also not allowed to modify func1() function", I doubt they want to modify the console.log call either.
This reply made me realize all options. Thanks.
@Bergi, you are right, it might not be ideal, but as you correctly stated, there is no other way if OP can't modify func1(), as it will always return an array. I will update my answer accordingly.
1

This is not possible. func1() always returns an array with one element, it can never return [1,2], not matter what func2 does. You must modify its code.

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.