DR01D
DR01D

Reputation: 1365

Why does index sometimes operate unexpectedly in reduce() method?

I'm experimenting with .reduce() and in the test code below I attempt to set accumulator.key[index] to the value 1. By using a console.log I can see that index is cycling correctly from 0 through 3. However my code only sets accumulator.key[3] to the value 1. The first 3 accumulator.key[index] it leaves as undefined. This is totally baffling to me. I can't see why it wouldn't set all 4 keys to 1. Thanks for any help!

"use strict";

var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
	
output = testArray.reduce((accumulator, currentValue, index) => {
  accumulator.key = [];
  console.log(index);
  accumulator.key[index] = 1;
  return accumulator;
}, []);

console.log(output.key);

Upvotes: 0

Views: 28

Answers (2)

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

I am not sure about your use case to use .key on an array but if that is what you decided then just don't initialise it to an array on each iteration. And if you are afraid of getting an undefined in the first iteration then use a fallback empty array.

  accumulator.key = (accumulator.key || []);

"use strict";

var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
	
output = testArray.reduce((accumulator, currentValue, index) => {
  accumulator.key = (accumulator.key || []);
  console.log(index);
  accumulator.key[index] = 1;
  return accumulator;
}, []);

console.log(output.key);

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

You in every iteration with this statement accumulator.key = [] assign to the key property a new [], which removes the previous array reference. Pass an object instead an array and define the key property on it as array.

var testArray = ['fe', 'fi', 'fo', 'fum'];
var output;
	
output = testArray.reduce((accumulator, currentValue, index) => {
  console.log(index);
  accumulator.key[index] = 1;
  return accumulator;
}, { key: [] });

console.log(output.key);

Upvotes: 2

Related Questions