LoginSignup
0
0

More than 3 years have passed since last update.

配列操作メソッド

Last updated at Posted at 2021-04-17

forEach

配列データに対してforEachを実行すると、配列データの値1つずつに対してコールバック関数に記述した処理を実行できる。

配列の中身を取得

const items = ['りんご','バナナ','もも','ブドウ'];
items.forEach(value => {
  console.log(value);
});//りんごバナナももブドウ)

map

  • 関数内に実行したい処理を書いておくことで、配列の各要素に対して好きな操作ができる
  • 「forEach」との違いは、「map」は実行後の結果を配列データとして返すこと
  • 元となる配列から新しい配列を作成できる
const array = [1,2,3,4,5,6,7];
const newArray = array.map(value => value * 3)
console.log(newArray);//[3,6,9,12,15,18,21]

find

提供されたテスト関数を満たす配列内の 最初の要素の値を返す
trueを返す要素が見つかるまで、要素に対して一度ずつ関数を実行する。

const before = [25,40,230,280];
const after = before.find(param => {
  return ((param % 20) === 0);
});
console.log(after);//40

filter

全ての要素に対して関数を一度ずつ実行し、戻り値(return)で true を返した要素からなる新しい配列を生成する。
mapとは異なり、trueを返した要素のみの配列を返し、生成された配列の値には実行時の要素の値が格納される。

const before = [25,40,230,280];
const after = before.filter(param => {
  return ((param % 20) === 0);
});
console.log(after);//[40,280]

some

trueを返す要素が見つかるまで、要素に対して一度ずつ関数を実行する。
trueを返す要素が見つかると、trueを返す。

const list = [10, 20, 30, 40];
const retVal = list.some(param => {
 console.log(param);
 return (param >= 20);
});
>10
>20
console.log(retVal)//true

evey

false を返す要素が見つかるまで、要素に対して一度ずつ関数を実行する。
falseを返す要素が見つかると、falseを返す。

const list = [10, 20, 30, 40];
const retVal = list.every(param => {
 console.log(param);
 return (param >= 20);
});
>10
console.log(retVal);//false

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