Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@s-takizawa

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

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]

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What are the problem?