Help us understand the problem. What is going on with this article?

備忘録 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]

参考

https://www.sejuku.net/blog/21887

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした