2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ES6メソッドの復習 map(), filter(), findIndex(), test()

Posted at

ES6の配列メソッド

  • 使わなくても別の構文で書ける
  • シンプルに書ける
  • 実行速度が早いわけではない

map()

  • 配列をイテレートする
  • 要素1つずつ処理する
  • 新しい配列を生成する
const array = [1, 2, 4, 8];
const resultArray = array.map(x => x * 2)
console.log(resultArray)
// output: Array [2, 4, 8, 16]

const object = {
    "hoge": {text: "fuga"},
    "foo":  {text: "bar" },
    "fiz":  {text: "buzz"}
};

const objectToArray = Object.keys(object).map(key => {
    const value = object[key]
    value['id'] = key
    return value
});

console.log(objectToArray)
/*
output: 
[
  { text: 'fuga', id: 'hoge' },
  { text: 'bar', id: 'foo' },
  { text: 'buzz', id: 'fiz' }
]
*/

filter()

  • 配列をイテレートする
  • 条件がtrueの要素のみ返す
const objectArray = [
    { id: "hoge", text: "fuga" },
    { id: "foo",  text: "bar"  },
    { id: "fiz",  text: "buzz" }
];

const result = objectArray.filter(object => {
    return object.id === 'hoge'
})

console.log(result)
// output: [ { id: 'hoge', text: 'fuga' } ]

findIndex()

  • 配列をイテレートする
  • 条件がtrueの要素が「何番目なのか」を返す
const objectArray = [
    { id: "hoge", text: "fuga" },
    { id: "foo",  text: "bar"  },
    { id: "fiz",  text: "buzz" }
];

const index = objectArray.findIndex(object => {
    return object.id === 'hoge'
})

console.log(index)
// output: 0

test()

  • 正規表現を使う
  • マッチする場合、trueを返す
  • マッチしない場合、falseを返す
const hoge = "hoge";
const hogefoo = "hogefoo";
const regex = RegExp("hoge*");

console.log(/hoge*/.test(hogefoo)); // true 
const isHoge = regex.test(hogefoo); // true

if (isHoge) {
  console.log("OK");
} else {
  console.log("NG");
}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?