LoginSignup
2
0

More than 3 years have passed since last update.

【JS】reduceとconcatで新たな配列を作成する方法とforEachでの書き換え。

Posted at

個人メモです。

reduceとconcatを使うことで新たな配列を作成することができる。

目次

  1. reduce & concat
  2. forEach & concat
  3. forEach & push
  4. reduce & push

reduce & concat

例えば、index番号が偶数の場合のみ要素を取り出す処理の場合

reduce
arr = ["a", "b", "c", "d"]

res = arr.reduce( (ary, elem, index) => {
    if (index % 2 == 0 ){
        return ary.concat(elem)
    } else {return ary}
}, [])

console.log(res)
// ["a", "c"]

▼ポイント

・reduceの初期値に[]をセット

.reduce( (処理結果, 要素, インデックス番号) => 処理, 初期値 )

・concatなので非破壊処理


forEach & concat

同様の処理をforEachで書くこともできる。

arr = ["a", "b", "c", "d"]

res2 = []
arr.forEach( (elem, index) => {
    if (index % 2 == 0 ){
        res2 = res2.concat(elem)
    }
})

console.log(res2)
// ["a", "c"]

▼ポイント

・事前に初期値[]を宣言しておく。
res2 = []


forEach & push

非破壊のconcatに対し、破壊的なpushで記述することも可能。

arr = ["a", "b", "c", "d"]

res = []
arr.forEach( (elem, index) => {
    if (index % 2 == 0 ){
        res.push(elem)
    }
})

console.log(res)
// ["a", "c"]


reduce & push

reduceでも破壊のpushを使って記述することができる。

arr = ["a", "b", "c", "d"]

res2 = arr.reduce( (ary, elem, index) => {
    if (index % 2 == 0 ){
        ary.push(elem)
        return ary
    } else {return ary}
}, [])

console.log(res2)
// ["a", "c"]

▼ポイント

・reduceは各処理毎に一つの処理結果を返す必要があるため、aryをpushで破壊処理した後、return aryを返す。


filter

本来の目的とは外れるが、今回の処理であればfilterを使うことも可能。

arr = ["a", "b", "c", "d"]

res4 = arr.filter( (elem, index) => {
    return index % 2 == 0
})

console.log(res4)
// ["a", "c"]

▼ポイント
filterはtrueかfalseを返す必要があるため、if
のカッコ内の条件式と異なりreturnが必要

2
0
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
0