みかづきブログ・カスタム

基本的にはちょちょいのほいです。

Array.prototype.mapを使って作成した配列からundefinedを削除したい 💻


const arr = ['a', 'b', 'c', 1, 2, 3].map((item) => {
  if (typeof item === 'number') {
    return item * 2;
  }
});

console.log(arr); // => [undefined, undefined, undefined, 2, 4, 6]

みたいなケースで、undefinedを削除したい場合、filterを使って、

const arr = ['a', 'b', 'c', 1, 2, 3].map((item) => {
  if (typeof item === 'number') {
    return item * 2;
  }
}).filter(Boolean);

console.log(arr); // => [2, 4, 6]

とすれば、手軽にundefinedを削除することができます。
なぜならば、filterに渡したBooleanでfalsyな値を削除できるからです。

しかし、

const arr = ['a', 'b', 'c', 0, 1, 2].map((item) => {
  if (typeof item === 'number') {
    return item * 2;
  }
}).filter(Boolean);

console.log(arr); // => [0, 2, 4]が欲しいのに[2, 4]となる

という具合に、undefined以外のfalsyな値も削除されることが、ときに問題を巻き起こす場合もあります。

そんなときは、

const arr = ['a', 'b', 'c', 0, 1, 2].map((item) => {
  if (typeof item === 'number') {
    return item * 2;
  }
}).filter((item) => item !== undefined);

console.log(arr); // => [0, 2, 4]

とすれば、確実にundefinedだけを除去できるので安全です。

ただし、今回の例であれば、

const arr = ['a', 'b', 'c', 0, 1, 2].filter((item) => typeof item === 'number').map((item) => {
  if (typeof item === 'number') {
    return item * 2;
  }
});

console.log(arr); // => [0, 2, 4]

というように、先にfilterをかけた方がわかりやすいです。