Is there a way to get the array being generated by the map function, inside the map function? For e.g.
let arr = [1, 2, 3, 4];
arr.map(item => {
console.log(currentArray);
return item * item;
}
So, in the above example, if at line 3 (currentArray), I want below output, how can I get that.
[1]
[1, 4]
[1, 4, 9]
The "array" parameter in map callback, returns the original array on which map function is called. Or do I need to go conventional for loop route to achieve this?
array#reduce?.map(), you could useforEachmethod. Declare an empty array which will hold the sub arrays and usingforEach, iterate over the array, adding new sub array in each iteration.arr.forEach((num, i) => res[i] = i > 0 ? [...res[i-1], num * num] : [num*num]);P.S:resis initially an empty array that will contain the sub-arrays afterforEachends.