skip to Main Content

I’m creating a set from two arrays, and I’m encountering a confusing TypeError:

const a_list = [1, 2, 3];
const b_list = [3, 4, 5];
const combined = new Set()
    .union(a_list)  // <<<< Error is thrown here.
    .union(b_list);

This fails with the error:

Uncaught TypeError: The .size property is NaN
    at Set.union (<anonymous>)
    at <anonymous>:2:6

How can the set’s .size property be NaN? When I test it in the console, the default size is 0:

> new Set().size
< 0

2

Answers


  1. Set.prototype.union() operates on values of Set, not arrays. The problem you’re seeing stems from the fact that [].size is undefined and Number(undefined) returns NaN. When you wrap both of your inputs in a Set, the issue is resolved.

    const a_list = new Set([1, 2, 3]);
    const b_list = new Set([3, 4, 5]);
    const combined = new Set()
        .union(a_list)
        .union(b_list);
    
    Login or Signup to reply.
  2. Sets have a size property, but arrays do not. And these are arrays:

    const a_list = [1, 2, 3];
    const b_list = [3, 4, 5];
    

    The union function on Set expects "a set-like object", and arrays are not that.

    You can convert them to sets:

    const a_list = [1, 2, 3];
    const b_list = [3, 4, 5];
    const combined = new Set()
        .union(new Set(a_list))
        .union(new Set(b_list));
    console.log(combined);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search