์กฐ๊ฑด์ ๋ง๋ ์์๋ง ๋ชจ์ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๋ค.
//filter()์ ์ธ์์์ ๋ฐ๋ก ํจ์ ์ฐ๋ ๋ฐฉ๋ฒ
let snacks = ['์ฝ์นฉ', '์์ฐ๊นก', '๊ฐ์๊นก', '๊ณ ๊ตฌ๋ง๊นก'];
let result = snacks.filter(snack => snack.includes('๊นก'));
console.log(result); //['์์ฐ๊นก', '๊ฐ์๊นก', '๊ณ ๊ตฌ๋ง๊นก']
let snacks = ['์ฝ์นฉ', '์์ฐ๊นก', '๊ฐ์๊นก', '๊ณ ๊ตฌ๋ง๊นก'];
const filterItems = (query) => {
return snacks.filter(snack => snack.indexOf(query) > -1);
}
console.log(filterItems('๊นก')); //['์์ฐ๊นก', '๊ฐ์๊นก', '๊ณ ๊ตฌ๋ง๊นก']
//๋ฐ์์ ํจ์๋ฅผ ์ ์ธํ๊ณ filter()์ธ์์์ call back
function aboveEighteen(number) {
return number > 18;
}
let numbers = [1, 5, 29, 499].filter(aboveEighteen);
console.log(numbers); //[29, 499]
function isEven(number) {
return number % 2 == 0;
}
let filtered_numbers = [1, 3, 4, 5, 24, 53].filter(isEven);
console.log(filtered_numbers); //[4, 24]
let students = [
{ id: 1, name: 'dabin', age: 25},
{ id: 2, name: 'isa', age: 27},
{ id: 3, name: 'joe', age: 28},
{ id: 4, name: 'jacob', age: 21},
];
const result = students.filter(student => student.age > 25);
console.log(result)
์ฃผ์ด์ง ๋ฐฐ์ด์ ๊ธฐ์กด ๋ฐฐ์ด์ ํฉ์ณ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๋ค. ์๋ณธ ๋ฐฐ์ด์ ๋ณํ์ง ์์ผ๋ฉฐ ์๋ก์ด๋ฐฐ์ด/์๋ณธ๋ฐฐ์ด ์์ ์์๋ ์๋ก ์ํฅ์ ์ฃผ์ง ์๋๋ค.
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = a.concat(b);
console.log(c);//[1, 2, 3, 4, 5, 6]
let d = [7, 8, 9];
let c = a.concat(b, d);
console.log(c);//[1, 2, 3, 4, 5, 6, 7, 8, 9]
๋ฐฐ์ด ์์ ๋ฐฐ์ด์ ํฉ์น ๋ (1depth๋ง ์ ์ฉ)
let a = [1, 2];
let b = a.concat([3, 4], [5, 6]);
console.log(b) // [1, 2, 3, 4, 5, 6]
let c = a.concat(3, [4, 5, [6]]);
console.log(c) // [3, 4, 5, [6]]
์ค๋ณต์ด ์๋ ๋ฐฐ์ด ๋ง๋ค๊ธฐ
let a = [1, 2, 3];
let b = [2, 3, 4, 5];
let c = a.concat(b);
console.log(c);//[1, 2, 3, 2, 3, 4, 5]
let eraseDuplicates = c.filter(el,index)=>
c.indexOf(el)===index);
console.log(eraseDuplicates);//[1, 2, 3, 4, 5]
๋ฐฐ์ด์ ๋ง๋๋ ๋ฐฉ๋ฒ์ []๋ฅผ ์ฌ์ฉํ๋ ๊ฒ ์ด์ธ์ new Array(n) ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ด ์๋ค. ์ด ๋ฉ์๋๋ n๊ฐ์ ์์๋ฅผ ๊ฐ์ง ๋ฐฐ์ด์ ๋ง๋ ๋ค. ๋น ๋ฐฐ์ด์ด๋ arr.length๋ฅผ ์ฐ์ผ๋ฉด 4๊ฐ ๋์จ๋ค. ๊ฐ์ ํ ๋นํ๋ ค๋ฉด ๋ฐ๋ณต๋ฌธ์ ์ด์ฉํ๋ฉด ๋๋ค.
function makeSquare () {
let arr = new Array(10)
for (let i = 0; i < arr.length; i++) {
arr[i] = i ** 2
}
return arr;
}