How to filter only values with type Symbol in an array?

Viewed 300

I'm working on arrow library where I'm creating a function that returns only elements with type Symbol.

I use the filter function on an array :

export const extractSymbol = array => {
    if (isArray(array)) {
        return array.filter(value => typeof value === "symbol")
    }
}

But because I'm creating tests before the implementation, This test fail :

  expect(extractSymbol([1, 2, 4, Symbol('vue'), Symbol('react')])).toStrictEqual([Symbol('vue'), Symbol('react')]);
   

I expected true but it returns :

 Expected: [Symbol(vue), Symbol(react)]
 Received: serializes to the same string
2 Answers

Two symbols created with the same parameter are not equal to each other:

console.log(
  Symbol('foo') === Symbol('foo')
);

For the test to work properly, define the symbols outside the expect, so you can pass the same reference to both arrays:

const s1 = Symbol('vue');
const s2 = Symbol('react');
expect(extractSymbol([1, 2, 4, s1, s2])).toStrictEqual([s1, s2]);

Try this:

let arr = [Symbol('foo'), 123];

let filtered = arr.filter(x => typeof(x) == 'symbol');
console.log(filtered);

Related