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.
JavaScript
x
16
16
1
const test = func1();
2
3
console.log(test); // actual: [[1,2]] what I want: [1,2]
4
5
function func1() { // not allowed to modify func1
6
return [func2()];
7
}
8
9
function func2() {
10
const set = new Set();
11
set.add(1);
12
set.add(2);
13
return Array.from(set);
14
// return Array.from(set).values() returns Array Iterator
15
}
16
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.
JavaScript
1
22
22
1
const test = func1();
2
3
function func1() { // not allowed to modify func1
4
return [func2()];
5
}
6
7
function func2() {
8
const set = new Set();
9
set.add(1);
10
set.add(2);
11
return Array.from(set);
12
// return Array.from(set).values() returns Array Iterator
13
}
14
15
// First element in array
16
console.log(test[0]);
17
18
// Array.flat()
19
console.log(test.flat());
20
21
// Spread operator
22
console.log(test);