1. map()
; 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환
ex1) numbers의 요소들 각각에 2배를 하여 doubleNumArray에 반환
const numbers = [1,2,3]
const doubleNumArray = numbers.map(num=>num*2)
console.log(doubleNumArray) // [2,4,6]
ex2) number의 요소들을 Number화 시키기
const numbers = ['1','2','3']
console.log(numbers.map(Number))
ex3) map과 assign을 이용한 예시
let userList = [
{ name: "Mike", age: 30 },
{ name: "Jane", age: 27 },
{ name: "Tom", age: 10 }
];
let newUserList = userList.map((user, index) => {
return Object.assign({}, user, {
id: index + 1,
isAdult: user.age > 19
});
});
console.log(newUserList);
2. filter()
; find와 사용법 동일 / find와 달리, 만족시키는 모든 요소를 배열로 반환
ex1) filter()을 활용한 검색하는 함수
notes={notes.filter((note) =>
note.text.toLowerCase().includes(searchText)
)}
; notes를 하나씩 꺼내 note에 넣음 -> 각각의 note의 text가 searchText를 포함하고 있으면 notes 배열로 재구성
ex2) filter()를 활용한 요소를 삭제하는 함수
const deleteNote = (id) => {
const newNotes = notes.filter((note) => note.id !== id);
setNotes(newNotes);
}
; notes를 하나씩 꺼내 note에 넣음 -> 각각의 note의 id가 인수로 받은 id와 일치하지 않는 것들로만 newNotes를 구성
ex3) 값이 3이상인 요소 추출
data.filter((it) => it.emotion>=3)
3. reduce()
; 누산기가 포함되어 있어, 배열의 각 요소에 대해 함수를 실행하고 누적된 값을 출력할 때 용이
reduce(callback,initialValue)
# initialValue ; callback의 최초 호출에서 첫 번째 인수에 제공되는 값. 제공안할 시 배열의 첫 번째 요소 사용
ex1) 누적합
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
// previousValue는 이전까지 계산된 값 / currentValue는 현재 취할 값
console.log(sumWithInitial); // 10
여기서 callback함수는 (previousValue,currentValue)=>previousValue+currentValue 이고 initialValue는 initialValue(0)이다.
ex2) 초기값이 10인 누적합
const arr2 = [1, 2, 3, 4, 5];
const result2 = arr2.reduce((acc, cur, idx) => { return acc += cur; }, 10);
console.log(result2); // 25
ex3) 객체배열에서 age가 25보다 큰 요소만으로 배열 구성하기
let userList = [
{ name: "Make", age: 30 },
{ name: "Tom", age: 23 }
];
let result = userList.reduce((prev, cur) => {
if (cur.age > 25) {
prev.push(cur.name);
}
return prev;
}, []);
console.log(result);
4. find()
; 만족시키는 첫 요소 반환. 없을 경우 undefined 반환
array.find((element,index,array)=>{})
ex1) element값이 10보다 크면서, index가 3보다 큰 요소 반환
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element,index,array) => element > 10 & index>3 );
console.log(found); // 44
array.find(function)
ex2) find()안에 function을 넣어, function을 만족하는 값 반환
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }
4.1 findIndex()
; 만족시키는 첫 요소의 index 반환. 없을 경우 -1 반환
array.findIndex((element)=>{})
ex2) findIndex안에 element매게변수를 이용한 화살표함수 넣기
const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex(element=>element>13));
array.findIndex(function)
ex2) findIndex()안에 function을 넣어, functino 만족하는 값의 index 반환
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3
5. concat()
; 2개 이상의 배열을 merge할 때 사용
array.concat(array2,array3,...)
ex) array1과 array2를 합친 배열 array3
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // ["a", "b", "c", "d", "e", "f"]
const array4 = [...array1,...array2]
console.log(array4); // ["a", "b", "c", "d", "e", "f"]
// 더 범용적으로 쓸 수 있는 spread를 이용하면 되는데 굳이? spread가 최신 js에서 나온거라 예전에는 concat이 쓰였나보다.
6. slice()
; 잘라내, 깊은 복사하여 return
array.slice(end) / array.slice(start,end) / array.slice() ; 깊은 복사
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); //["camel", "duck", "elephant"]
console.log(animals.slice(2, -1)); //["camel", "duck"]
console.log(animals.slice()); //["ant", "bison", "camel", "duck", "elephant"]
7. forEach()
; 데이터값과 인덱스값을 모두 mapping
let arr = ["Mike", "Tom", "Jane"];
arr.forEach((name, index) => {
console.log(`${index + 1}번째 이름 ${name}`);
});
- indexOf(a,b) ; [b]부터 처음 나타나는 a 찾기
- lastIndexOf(a) ; 뒤에서부터 처음 나타나는 a 찾기
- includes(a) ; a를 포함하고 있는지 판별
- join(' ') ; 배열 요소들을 사이에 ' '를 넣어 하나의 문자열로 합쳐줌 / split(' ') ; 하나의 문자열을 ' '을 기준으로 배열요소들로 분리함
- sort(fn) ; fn을 기준으로 정렬
let arr = [24, 8, 5, 13];
// sort는 문자열 기반 정렬이기때문에, 위 요소들의 첫 번째 요소를 기준으로 정렬함
const fn = (a, b) => {
return a - b;
};
arr.sort(fn);
console.log(arr);
위처럼 함수를 매번 만드는 것이 번거롭기에, lodash 라이브러리를 사용
_.sortBy(arr)를 사용하면 숫자든, 문자든 원하는 대로 정렬해줌
'WebProgramming > JS' 카테고리의 다른 글
[JavaScript] 한 페이지 정리 (0) | 2022.07.26 |
---|---|
[JavaScript] Computed Property (0) | 2022.07.26 |
[JavaScript] Object Methods(assign,keys,values,entries,fromEntries) (0) | 2022.07.26 |
[JS] JS 라이브러리 (lodash, axios) (0) | 2022.06.30 |
[TS] 타입 별칭 & Interface (0) | 2022.06.24 |
[TS] TS의 타입 시스템? & Compliation Context (0) | 2022.06.12 |
[TS] TypeSCript이란? & 타입 (0) | 2022.06.12 |
[JS] JSON (0) | 2022.06.11 |