1
0

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 1 year has passed since last update.

JavaScriptの配列操作のまとめ(map/filter/find/every/some/reduce)

Last updated at Posted at 2022-12-26

はじめに

JavaScriptで配列を操作する時に使用する便利な各メソッドのまとめです。

map

すべての要素に対して1つずつ処理をして全ての要素を返す
↓mapを使用して数字を10倍した例

const numbers = [1,2,3];

const tenTimes = numbers.map((number) => {
  return number * 10
});

console.log(tenTimes); // [10, 20, 30]

filter

条件を満たした要素をすべて返す
↓filterを使用して2の倍数のみ抽出した例

const numbers = [1,2,3,4];

const result = numbers.filter((num) => {
  return num % 2 == 0
});

console.log(result); // [2, 4]

find

最初に条件を満たした要素1つだけ返す
↓findを使用して3以上の要素1つを抽出した例

const numbers = [1,2,3,4];

const result = numbers.find((num) => {
  return num >= 3 
});

console.log(result); // [3]

every

すべての要素が条件を満たしたらtrueを返す
↓everyを使用して要素が全て3以上かをチェックした例

const numbers = [1,2,3,4];

const result = numbers.every((num) => {
  return num >= 3 
});

console.log(result); // [false]

some

すべての要素のうち1つでも条件を満たしたらtrueを返す
↓someを使用して要素が全て3以上かをチェックした例

const numbers = [1,2,3,4];

const result = numbers.some((num) => {
  return num >= 3 
});

console.log(result); // [true]

reduce

すべての要素に対して処理をして、1つの要素を返す
↓reduceを使用して各要素の合計値を返す例

const numbers = [1,2,3,4,5];

const result = numbers.reduce((accumulation, element) => {
  return accumulation + element;
});

console.log(result); // [15]
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?