Himanshu
Himanshu

Reputation: 43

Get intermediate array in Javascript Map function

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?

Upvotes: 1

Views: 248

Answers (3)

micronyks
micronyks

Reputation: 55443

You can use reduce function as follow,

let arr = [1, 2, 3, 4];


arr.reduce((acc, item)=>{
   acc.push(item*item);
   console.log(acc);
   return acc;
}, []);



// SINCE YOU ARE ASKING HOW TO DO IT USING MAP
console.log('*******************************')

let arr1 = [1, 2, 3, 4];
const currentArray = [];
arr1.map(item => {
  currentArray.push(item * item);
  console.log(currentArray);
  return  item* item;
})

Upvotes: 1

sçuçu
sçuçu

Reputation: 3070

You can use the reduce instead of the map, but you do not have to by the way. Anyways, then you will have your accumulator as the first argument to the reducer callback. The variable accumulator will hold the intermediate states of the value to be returned.

let arr = [1, 2, 3, 4];
let result = arr.reduce((accumulator, item) => {
  console.log("currentArray accumulator: ", accumulator);
  return [...accumulator, item * item];
}, []);

There is a neat another answer around which uses map and do what you want. So, yes it is possible to achieve same with map and reduce is a convenience function that actually is a special case map function itself.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386736

You could map the squares by using a closure over ta temporary result set.

let array = [1, 2, 3, 4],
    result = array.map((t => v => t = [...t, v * v])([]));

console.log(result);

Upvotes: 2

Related Questions