JavaScript .filter() ๋ฉ”์„œ๋“œ ๐Ÿ’ญ

4694 ๋‹จ์–ด functionalwebdevjavascriptbeginners
๊ทธ๋ž˜์„œ ์˜ค๋Š˜์€ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ .filter() ๋ฉ”์†Œ๋“œ์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

ํ•„ํ„ฐ ๋ฐฉ๋ฒ•



JavaScript์˜ filter() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ๋ฅผ ๊ฐ€์ ธ์™€ ์กฐ๊ฑด๋ฌธ์„ ์ ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด ์กฐ๊ฑด๋ฌธ์ด true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์š”์†Œ๊ฐ€ ์ถœ๋ ฅ ๋ฐฐ์—ด๋กœ ํ‘ธ์‹œ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์š”์†Œ๊ฐ€ ์ถœ๋ ฅ ๋ฐฐ์—ด๋กœ ํ‘ธ์‹œ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

filter() ๋ฉ”์„œ๋“œ๋Š” ๊ธฐ์กด ๋ฐฐ์—ด์—์„œ ์ฃผ์–ด์ง„ ๊ธฐ์ค€์— ์†ํ•˜๋Š” ์š”์†Œ๋กœ ์ƒˆ ๋ฐฐ์—ด์„ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

ํ†ต์‚ฌ๋ก 




var first_array = arr.filter(
    function callback(element, index, array) {
        // Returns true or false
}[, thisArg])


filter์˜ ๊ตฌ๋ฌธ์€ map์˜ ๊ตฌ๋ฌธ๊ณผ ๋น„์Šทํ•˜์ง€๋งŒ ์š”์†Œ๋ฅผ ์œ ์ง€ํ•˜๋ ค๋ฉด ์ฝœ๋ฐฑ ํ•จ์ˆ˜๊ฐ€ true๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•˜๊ณ  ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ฝœ๋ฐฑ์—์„œ๋Š” ์š”์†Œ๋งŒ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ



์•„๋ž˜ ์ฃผ์–ด์ง„ ์˜ˆ์—์„œ ํ™€์ˆ˜๋Š” "ํ•„ํ„ฐ๋ง"๋˜์–ด ์ง์ˆ˜๋งŒ ๋‚จ์Šต๋‹ˆ๋‹ค.

const all_numbers = [1, 2, 3, 4];
const even_numbers = all_numbers.filter(number => number % 2 === 0);
console.log(even_numbers);
// [2, 4]


๋‹ค์Œ ์˜ˆ์—์„œ filter()๋Š” ์„ฑ์ ์ด 90 ์ด์ƒ์ธ ๋ชจ๋“  ํ•™์ƒ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

const students = [
    { name: 'Mursal', grade: 96 },
    { name: 'Furqan', grade: 48 },
    { name: 'Ahmed', grade: 99 },
    { name: 'Anees', grade: 56 },
    { name: 'Burhan', grade: 90 }
];

const studentGrades = students.filter(
    students => students.grade >= 90);
return studentGrades;

//[ { name: 'Mursal', grade: 96 },
//    { name: 'Ahmed', grade: 99 },
//    { name: 'Burhan', grade: 90 } ]


๋‹ค์Œ ๊ธฐ์‚ฌ์—์„œ๋Š” ๋” ๋ฉ‹์ง„ ๊ฒƒ์— ๋Œ€ํ•ด ๋…ผ์˜ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ