shou2017.com
JP

Extracting items that match conditions using JavaScript filter

Fri Feb 19, 2021
Sat Aug 10, 2024

What I want to do

Nobita has several friends. Nobita wants to know the characteristics of his new friends. However, the only place where the friends’ characteristics are listed is the student roster.

But the student roster contains 900 students. If you check by hand, you won’t make it in time for tomorrow’s picnic.

So, Nobita decided to solve this by writing a JavaScript script.

Data brought from school


// Nobita's data
const nobitaData = {
  'friends': [
    'Suneo',
    'Doraemon',
    'Gian'
  ]
};

// Student roster
const studentList = 
[
  {
    'trait': 'Rich',
    'name': 'Suneo'
  }
  ,
  {
    'trait': 'Cat-type robot',
    'name': 'Doraemon'
  }
  ,
  {
    'trait': 'Strongman',
    'name': 'Gian'
  }
  ,
  {
    'trait': 'Madonna',
    'name': 'Shizuka'
  }
  ,
  {
    'trait': 'Good at studying',
    'name': 'Dekisugi'
  },
  {
    'trait': 'Common surname',
    'name': 'Tanaka'
  },
  {
    'trait': "Gian's sister",
    'name': 'Jaiko'
  }
];

Let’s try

I wrote it in a bit of a joking manner, but I think it’s a valid condition even in actual programs.

So, what will you do?

First of all, the filter method seems usable.

However, with just filter, it’s impossible to check all friends, right? It seems possible to prepare an empty array, loop with a For Loop, and push it to the empty array created earlier.

So, how about this?

const nobitaNoFriends = nobitaData.friends;
let friendInClass = [];
for (let i = 0; i < nobitaNoFriends.length; i++) {
  studentList.filter(function (human) {
    if (human.name === nobitaNoFriends[i]) {
      friendInClass.push(human);
    }
  });
}
console.log(friendInClass);

It worked.

[
  { trait: 'Rich', name: 'Suneo' },
  { trait: 'Cat-type robot', name: 'Doraemon' },
  { trait: 'Strongman', name: 'Gian' }
]

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで

See Also