-1

I am trying to flatten an array with the following code, but when I use .flatMap() I get the error:

Uncaught TypeError: flatMap mapper function is not callable
    at Array.flatMap (<anonymous>)
const data = [
        { key1: 5, key3: 2 },
        { key1: 2, key3: 1 },
        { key1: 3, key3: 2 },
        { key2: 8 },
        { key1: 5, key3: 2 },
      ];
var allKeys = data.map(r => Object.keys(r))
// [
//   [ 'key1', 'key3' ],
//   [ 'key1', 'key3' ],
//   [ 'key1', 'key3' ],
//   [ 'key2' ],
//   [ 'key1', 'key3' ]
// ]
allKeys.flatMap();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Max888
  • 3,089
  • 24
  • 55

2 Answers2

1

In this case I should be using flat() not flatMap(). The below works as expected.

const data = [
    { key1: 5, key3: 2 },
    { key1: 2, key3: 1 },
    { key1: 3, key3: 2 },
    { key2: 8 },
    { key1: 5, key3: 2 },
];
var allKeys = data.map(r => Object.keys(r))
console.log(allKeys.flat());
Ziaullhaq Savanur
  • 1,848
  • 2
  • 17
  • 20
Max888
  • 3,089
  • 24
  • 55
1

You could use flatMap instead of map to be more concise, which eliminates the need for calling .flat() after, as it is just shorthand for .map(...).flat(). As well, you can directly pass Object.keys as the callback for flatMap, as it ignores all arguments other than the first one that it is given.

const data = [
        { key1: 5, key3: 2 },
        { key1: 2, key3: 1 },
        { key1: 3, key3: 2 },
        { key2: 8 },
        { key1: 5, key3: 2 },
      ];
var allKeys = data.flatMap(Object.keys)
console.log(allKeys);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80