885
837

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でforEach, filter, map, reduceとか

Last updated at Posted at 2014-12-20

IE8もそろそろ死んでくれそうで、最近は使うことが多いのでメモ。

参考URL

ここをみると、全部のってる。

forEach

連想配列(object)だと使えないので、eachはjQueryの$.each(collection, callback)の方が使い勝手がいいかも。

[2, 5, 9].forEach(function(element, index, array) {
	console.log(index + ":" + element);
	/**
	 * 0:2
	 * 1:5
	 * 2:9
	 */
});

filter

条件にあうものだけを抽出。
arrayは元の配列。index, arrayは省略可能。

var filtered = [12, 5, 8, 130, 44].filter(function(element, index, array) {
    return (element >= 10);
});

console.log(filtered); // [ 12, 130, 44 ]

map

処理をして新しい配列を作る(写像ですね)。
arrayは元の配列。index, arrayは省略可能。

var square = [1, 2, 3, 4, 5].map(function(element, index, array) {
    return element * element;
});

console.log(square); // [ 1, 4, 9, 16, 25 ]

reduce, reduceRight

処理をして1つの値を取得。
previousValueは前の値というより、それまでの結果と考えるとわかりやすい。
arrayは元の配列。index, arrayは省略可能。

var total = [0, 1, 2, 3].reduce(function(previousValue, currentValue, index, array) {
    return previousValue + currentValue;
});

console.log(total); // 6

reduceRightは右から処理する。

var total = [0, 1, 2, 3].reduceRight(function(previousValue, currentValue, index, array) {
    return previousValue + currentValue;
});

console.log(total); // 6

every, some

everyは条件を全ての値が満たすか、someは条件を満たすものがあるかの判定。
結果はboolean。
arrayは元の配列。index, arrayは省略可能。

var passed = [12, 54, 18, 130, 44].every(function(element, index, array) {
    return (element >= 10);
});

console.log(passed); // true
passed = [2, 5, 8, 1, 4].some(function(element, index, array) {
    return (element >= 10);
});

console.log(passed); // false
885
837
2

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
885
837

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?