filter() で配列から条件に合った要素を取り出す

配列というか JSON オブジェクトの検索に。

const fruits = [
	{
		"name":"Apple",
		"price":100,
		"color":"red"
	},
	{
		"name":"Orange",
		"price":150,
		"color":"orange"
	},
	{
		"name":"Strawberry",
		"price":200,
		"color":"red"
	},
	{
		"name":"Pineapple",
		"price":250,
		"color":"yellow"
	}
]

const nameFilteredFruits = fruits.filter( function(fruit) {
	return fruit.name === 'Apple'; //名前が「Apple」なもの
})
console.log(nameFilteredFruits)
//[{name: "Apple", price: 100, color: "red"}]

const priceFilteredFruits = fruits.filter( function(fruit) {
	return fruit.price <=  150; //値段が150円以下のもの
})
console.log(priceFilteredFruits)
//[{name: "Apple", price: 100, color: "red"}, {name: "Orange", price: 150, color: "orange"}]

const colorFilteredFruits = fruits.filter( function(fruit) {
	return fruit.color ===  'red'; //色が赤いもの
})
console.log(colorFilteredFruits)
//[{name: "Apple", price: 100, color: "red"}, {name: "Strawberry", price: 200, color: "red"}]

const nameLikeFilteredFruits = fruits.filter( function(fruit) {
	return fruit.name.match(/Apple/i); //名前が「Apple」を含むもの(大文字小文字問わず)
})
console.log(nameLikeFilteredFruits)
//[{name: "Apple", price: 100, color: "red"}, {name: "Pineapple", price: 250, color: "yellow"}]

filter という名前がピンとこないけど Excel のオートフィルタと同じと思えばなるほど。こんなん知らないと for ループまわしちゃうよねぇ。

Array.prototype.filter()