TypeError: Reduce of empty array with no initial value

Message

TypeError: ์ดˆ๊ธฐ๊ฐ’์ด ์—†๋Š” ๋นˆ ๋ฐฐ์—ด์— ๋Œ€ํ•œ recude๋Š” ์—๋Ÿฌ

Error type

What went wrong?

์ž๋ฐ”์Šคํฌ๋ฆฝํฌ์—์„œ ๋ช‡ ๋ช‡์˜ reduce ํ•จ์ˆ˜๋“ค:

์ด๋Ÿฌํ•œ ํ•จ์ˆ˜๋“ค์€ ์„ ํƒ์ ์œผ๋กœ ์ดˆ๊ธฐ๊ฐ’(initialValue)์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.(์ฝœ๋ฐฑ(callback)์˜ ์ฒซ๋ฒˆ์งธ ํ˜ธ์ถœ์— ๋Œ€ํ•œ ์ฒซ๋ฒˆ์งธ ์ธ์ˆ˜๋กœ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.) ๊ทธ๋Ÿฌ๋‚˜, ๋งŒ์•ฝ์— ์ดˆ๊ธฐ๊ฐ’์„ ์„ค์ •ํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, Array or TypedArray์— ๋Œ€ํ•œ ์ฒซ๋ฒˆ์งธ ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ ์‚ฌ์šฉ ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์— ์ดˆ๊ธฐ๊ฐ’์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋นˆ ๋ฐฐ์—ด์ด ์ œ๊ณต๋  ๊ฒฝ์šฐ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒ ํ•ฉ๋‹ˆ๋‹ค.

Examples

Invalid cases

This problem appears frequently when combined with a filter (Array.prototype.filter(), TypedArray.prototype.filter()) which will remove all elements of the list. Thus leaving none to be used as the initial value.

var ints = [0, -1, -2, -3, -4, -5];
ints.filter(x => x > 0)         // removes all elements
    .reduce((x, y) => x + y)    // no more elements to use for the initial value.

Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:

var names = document.getElementsByClassName("names");
var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);

Valid cases

These problems can be solved in two different ways.

One way is to actually provide an initialValue  as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.

var ints = [0, -1, -2, -3, -4, -5];
ints.filter(x => x > 0)         // removes all elements
    .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition

Another way would be two to handle the empty case, either before calling reduce, or in the callback after adding an unexpected dummy initial value.

var names = document.getElementsByClassName("names");

var name_list1 = "";
if (names1.length >= 1)
  name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
// name_list1 == "" when names is empty.

var name_list2 = Array.prototype.reduce.call(names, (acc, name) => {
  if (acc == "") // initial value
    return name;
  return acc + ", " + name;
}, "");
// name_list2 == "" when names is empty.

See also