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

備忘録 Javascript 配列のデータ抽出 filter

Last updated at Posted at 2020-09-15

Javascript filter

基本(数字)

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

var result = array.filter((value)=>{
    //valueには配列の要素が入る(1 2 3 ... 9 10)
    //valueが5よりも小さい数だけ抽出
    return value < 5;
})

console.log(result);
// [1, 2, 3, 4] という新しい配列ができる。

基本②(文字列)

var string_array = ["apple", "orange", "peach", "lemon"];

var result = string_array.filter((value) => {
    return value === "apple" || value == "orange";
})

console.log(result);
//["apple", "orange"] という新しい配列ができる。

重複を操作

var array = [2, 3, 4, 5, 3, 4, 5, 6, 7, 8, 6];

var result = array.filter((value, index, array) => {
    return array.indexOf(value) === index;
})
console.log(result);
//[2, 3, 4, 5, 6, 7, 8]

オブジェクト

※ array.filter(callback,object)とするとthisでobjectを参照できる。

var students_id = {
    1: "tanaka",
    2: "suzuki",
    3: "sato",
    4: "nakata",
    5: "nakamura" 
}

var ids = [1, 2, 3, 5, 7, 8, 9];

var result = ids.filter(function(value){
    for(var id in this){
        if(id == value){
            return value;
        }
    }
},students_id)

console.log(result);
//[1, 2, 3, 5]

参考

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?