10
6

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 5 years have passed since last update.

【javascript】ES6(ES2015) Array ループメソッド

Last updated at Posted at 2019-10-15

概要

javascript(es6)のArrayの処理についてのメモになります。
今さらな感じはありますが、es6に関して疎い部分が多くあったため再度学習した内容の備忘です。
(学習内容については進度毎に、更新また別記事作成予定です。)

index 内容
1 Arrayループメソッド
2 varとletとconst

※findIndexを追加、更新しました。(10/16/2019)
varとletとconstを追加しました(10/17/2019)

ループメソッド

forEach

  • 配列内の要素毎に関数を呼び出す
foreach_1.js
let nums = [1, 2, 3]
let sum = 0;
let idx = [];
let ary = [];

nums.forEach((item, index, array) => {
  sum += item;
  idx.push(index);
  ary.push(array);
})

sum // => 6
idx // => [0,1,2]
ary // => [[1,2,3],[1,2,3],[1,2,3]]
foreach_2.js
let products = [
  { "name": "apple", "number": 100, "price": 300 },
  { "name": "orange", "number": 60, "price": 150 },
  { "name": "peach", "number": 250, "price": 400 }
];
let sales = [];

products.forEach(product => {
  sales.push(product.number * product.price);
})
sales
// sales => [30000,9000,100000]

map

  • 配列内の要素毎に関数を呼び、その結果を新しい配列に格納して返す
map.js
let images = [
  { "height": 10, "width": 30 },
  { "height": 20, "width": 90 },
  { "height": 54, "width": 32 }
];

let areas = images.map(image => {
  return image.height * image.width;
});
// areas => [300, 1800, 1728]
  • pluck関数
    第2引数にオブジェクトのkeyを渡し、keyに対応するvalueを返す
pluck.js
function pluck(array, prop){
  const obj = array.map(prev => {
    return prev[prop];
  })
  return obj;
}

let animalArray = [{ "name": 'cat' },{ "name": 'dog' }, { "name": 'tiger' }];

let animalNames = pluck(animalArray, 'name');
// animalNames => ["cat","dog","tiger"]

filter

  • 配列内の要素毎を、指定したフィルタリング関数を通し、結果が'true'時に、配列内の要素を取り込み新しい配列を返す
filter_1.js
let products = [
  {"type": "f", "name": "apple", "price": 200},
  {"type": "v", "name": "carrot", "price": 50},
  {"type": "v", "name": "onion", "price": 30},
  {"type": "f", "name": "banana", "price": 40},
];

let filterdProduct = products.filter(product => {
  return product.type === "f" && product.price > 100;
})
// filterdProduct => [{"type":"f","name":"apple","price":200}]
filter_2.js
let allPost = [
  {"id": 1, "title": "for the very first time"},
  {"id": 2, "title": "recently"},
  {"id": 3, "title": "byebug"}
];

let allComment = [
  {"postid": 1, "body": "nice"},
  {"postid": 3, "body": "byebye"},
  {"postid": 2, "body": "wow"},
  {"postid": 2, "body": "good"}
];

function commentsOfPost(posts, comments){
  return comments.filter(comment => {
    return comment.postid === 2; 
  });
}

commentsOfPost(allPost, allComment);
// => [{"postid":2,"body":"wow"},{"postid":2,"body":"good"}]
  • reject関数
    配列内の要素毎を、指定したフィルタリング関数を通し、結果が'false'時に、配列内の要素を取り込み新しい配列を返す
reject.js
function reject(array, iteratorFunction) {
  const returnVal = array.filter(unit => {
    return iteratorFunction(unit) === false;
  });
  return returnVal;
}

let ages = [10, 20, 30, 40];
let teen = reject(ages, function(age){
  return age >= 20;
});
// teen => [10] 

find

  • 配列の要素毎で、指定した関数に適した時の最初の要素を返す
    適したものが見つからない場合、'undefined'を返す
find.js
let allPost = [
  {"id": 1, "title": "hello"},
  {"id": 2, "title": "gold"},
  {"id": 3, "title": "daylights"}
];

let cmt = {"postid": 1, "comment": "hi"};

function postOfComment(posts, comment){
  return posts.find(post => {
    return post.id === comment.postid;
  });
}

postOfComment(allPost, cmt);
// => {"id":1,"title":"hello"}
find.js
let allPost = [
  {"id": 1, "title": "hello"},
  {"id": 2, "title": "gold"},
  {"id": 3, "title": "daylights"}
];

let cmt = {"postid": 5, "comment": "nothing"};

function postOfComment(posts, comment){
  return posts.find(post => {
    return post.id === comment.postid;
  });
}

postOfComment(allPost, cmt);
// => undefined
  • findWhere関数
    第2引数にオブジェクトのkey,valueを渡して、指定した関数に適した最初の要素を返す
findWhere.js
function findWhere(array, attrs) {
  const key = Object.keys(attrs)[0];
  return array.find(unit => {
    return unit[key] === attrs[key];
  });
}

let members = [
  {"id": 1, "ages": 35},
  {"id": 2, "ages": 29},
  {"id": 3, "ages": 23},
  {"id": 4, "ages": 29}
]

findWhere(members, {"ages": 29});
// => {"id":2,"ages":29}

findIndex

  • 配列の要素毎で、指定した関数に適した時の最初の要素のインデックスを返す
    適したものが見つからない場合は'-1'を返す
let members = ["dave", "taylor", "nate", "pat", "chris"];

members.findIndex(member => {
  return member === "pat"
})
// => 3

members.findIndex(member => {
  return member === "peter"
})
// => -1

every

  • 指定した関数が、配列内の要素毎に確認し、結果を論理積で返す
every.js
let family = [
  {"name": "da", "age": 40},
  {"name": "mo", "age": 35},
  {"name": "me", "age": 12},
  {"name": "si", "age": 9}
];

family.every(person => {
  return person.age >= 10;
});
// => false

some

  • 指定した関数が、配列内の要素毎に確認し、結果を論理和で返す
some.js
let family = [
  {"name": "da", "age": 40},
  {"name": "mo", "age": 35},
  {"name": "me", "age": 12},
  {"name": "si", "age": 9}
];

family.some(person => {
  return person.age >= 40;
});
// => true

reduce

  • 配列内の要素に対して、関数を実行し、1つの値を返す
    (まだ内容が曖昧のため実験中です)
reduce.js
let trafficLights = [
  {"name": "red"},
  {"name": "yellow"},
  {"name": "green"}
];

trafficLights.reduce(function(previous, trafficLight){
  previous.push(trafficLight.name);
  return previous;
}, [])
// => ["red","yellow","green"]
  • unique関数
    配列内の要素内で、重複した要素を省いた値を返す
unique.js
let atoes = ["a","b","b","c","d","d","e"];

function unique(array){
  return array.reduce(function(prev, unit){
    let isIncluded = prev.find(foo => {
      return unit === foo;
    })
    if(!isIncluded){
      prev.push(unit);
    }
	return prev;
  }, [])
}

unique(atoes);
// => ["a","b","c","d","e"]

最後に

基本的には、某学習動画サイトやMDNのリファレンスで学習しています。
また、先駆者が内容をまとめている記事等を拝見しながらも進めております。(とても感謝です:relaxed:)
でも最終的には、MDNのリファレンスに戻ってきてしまいますね。

参考

Array - MDN - Mozilla
【javascript】reduce - Qiita

10
6
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
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?