5
3

More than 5 years have passed since last update.

javascriptのfilter, map, reduce, sort methodメモ

Last updated at Posted at 2015-12-13

Freecodecampで習ったarrayfiltermap辺りをもうちょっと調べてみたくなったので。ご飯食べながらこのビデオ見ながら、ちょっとだけ試してみる。コメントが英語と日本語ごっちゃになっていますが気にしないでください笑

example.js
var animals = [
    { name: 'taro',   species: 'sloth'},
    { name: 'satoko', species: 'dog'},
    { name: 'jake',   species: 'ibis'},
    { name: 'kyoko',  species: 'tarantula'},
    { name: 'doggy',  species: 'cat'},
    { name: 'sassy',  species: 'dog'}
]

という動物配列を作ってみる。

// animalsの名前を新たに作成した`names`配列に入れてくれるfunc

var names = []
for (var i = 0; i < animals.length; i++) {
    names.push(animals[i].name)
}
console.log(names)
// ある特定の動物だけを`selected_species`配列に入れてくれるfunc

var selected_species = []
for (var i = 0; i < animals.length; i++) {
    if (animals[i].species === '取得したいspecies')
        selected_species.push(animals[i])
}

たとえば、怠け者(動物)を探したい時、

// 怠け者(動物)を探すfunc

var sloth = []
for (var i = 0; i < animals.length; i++) {
    if (animals[i].species === 'sloth') // if the species of the animals being i, is 'sloth'
        sloth.push(animals[i])
}

filter methodを使ってもっと楽に

var sloth = animals.filter(function(animal) {
    return animal.species === 'sloth'
})

  1. filter methodの中に違う関数を入れる(callback funcって?
  2. そのファンクションが引数animalを取ってslothかどうかのTrue or false判定
  3. もしtrueならばそのままsloth配列に入れてくれる (push)

ちなみにこれは以下の二つに分けて考えることも出来る。

var isCat = function(animal) {
    return animal.species == 'cat'
}

var dogs = animals.filter(isCat)

map methodを使ってみる

mapの場合はfilterと違って新しい配列を作ってくれる。写像。

var names = animals.map(function(animal)) {
    return animal.name
}

これは多分下と同じ作業をしている。。。

var names = []
for (var i = 0; i < animals.length; i++) {
    names.push(animals[i].name)
}

Freecodecamp (Waypoint 175)に載っていたfilter methodを使った問題を問いてみる(追記)

問題: Use filter to remove all elements from array that are greater than 5

given_script.js
var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray;

// Only change code above this line.

(function() { return newArray; })();

5以上の数字を含まない配列を作るということは、newArray配列に5以下の数字を入れることと同じなので条件分岐でreturn val <= 5として5以下の数字を配列に入れてあげれば良い。

var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray.filter(function(val) {
  return val <= 5;
});

// Only change code above this line.

(function() { return newArray; })();

ついでにmethod reduceも

reduce methodを使えば配列の中に入っている数値valueを全てまとめて一つの数値にまとめたりできる。

var array = [1,2,3,4,5];

var singleVal = array.reduce(function(previousVal, currentVal) {
    return previousVal + currentVal;
}, 0);

ついでにsort method(追記)

参考にしたサイト: Sorting a JavaScript array using array.sort()

// Here is an example of using sort with a compare function that will sort the elements from smallest to largest number:

var array = [1, 12, 21, 2];

array.sort(function(a, b) {

  return a - b;

});

課題はこちら:

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort();

// Only change code above this line.

(function() { return array; })();

例題を参考に、

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a,b) {
  return b - a;
});

// Only change code above this line.

(function() { return array; })();

複数のmethodを一度に使ってみる

入力したinput`str`を逆さにして表記

function reverseString(str) {
  return str.split("").reverse().join('');
}

reverseString("hello"); // olleh

ご飯食べながら書いたのでもし間違えていたらごめんなさい。。。

5
3
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
5
3