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!
Advertisement
Answer
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);