최근 알고리즘 문제를 풀면서 느낀 것도 많았고 배운 것도 많았다
그중에서 크게 와닿는 것이 있었는데
바로 내장함수였다.
본인은 내장 함수를 거의 사용하지 않았다 ...
그래서 오늘은 내장함수에 대해서 복습하는 시간을 가지려고 한다!!
바로 시작해 보자
Array 내장함수
- join()
- split()
- reverse()
- splice()
- slice()
- find()
- some()
- every()
- reduce()
- sort()
- map()
- filter()
- forEach()
1. join()
join() 메소드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
원본 배열은 바꾸지 않음.
비파괴적 처리
let color = ['red','black','orange','blue','gray']
console.log(color.join()) // red,black,orange,blue,gray
console.log(color.join('')) // redblackorangebluegray
console.log(color.join(' and ')) // red and black and orange and blue and gray
console.log(color)// [ 'red', 'black', 'orange', 'blue', 'gray' ]
2. split()
string을 array로 만들어 주는 메소드.
원본 string은 변화시키지 않음.
비파괴적 처리
split에 구분자를 전달하지 않으면 문자열 전체가 배열의 한 요소로 들어가기 때문에 꼭 구분자를 전달해야 한다.
let members = '빈,민,뀨,쥬,햅,끼'
console.log(members.split()) // [ '빈,민,뀨,쥬,햅,끼' ] 배열의 0번째 인덱스에 모두 들어가버림
console.log(members.split('')) //['빈' , ',' , '민' , ',' , '뀨' , ',' , '쥬' , ',' , '햅' , ',' , '끼'] ,까지 배열의 인덱스에 들어감
console.log(members.split(','))// [ '빈', '민', '뀨', '쥬', '햅', '끼' ] 정상적으로 0부터 5까지 인덱스에 요소가 들어감
console.log(members) // 빈,민,뀨,쥬,햅,끼
3. reverse()
순서가 뒤집힌 배열을 반환해주는 배열 메소드.
원본 배열을 변환한다.
파괴적 처리
const array = ['a','b','c','d','e','f']
array.reverse();
console.log(array) // [ 'f', 'e', 'd', 'c', 'b', 'a' ] 배열 원본 자체가 바뀌어 버린다
4. splice()
인덱스로 시작부분과 끝나는 부분을 지정해주면, 지정된 부분을 삭제해줌.
그리고 삭제된 요소들이 return 된다.
원본 배열에서 데이터를 삭제하기 때문에 원본 배열을 변환한다. 배열 자체를 수정
파괴적 처리
let array = [1,2,3,4,5,6,7]
array.splice(0,2) // 0번째 인덱스부터 2개 삭제하겠다는 뜻!! array = [ 3, 4, 5, 6, 7 ] 가 된 상태!
array.splice(0,3) // 파괴적 처리이기 때문에 array = [ 3, 4, 5, 6, 7 ]가 되어있고 0번째 인덱스에서 다시 3개를 삭제!
console.log(array) // [ 6, 7 ]
5. slice()
배열의 특정 부분을 반환하는 배열메소드.
원하는 부분만 가지고 와 새로운 배열을 만들어야 한다면 slice()메소드를 사용.
원본 배열을 변경하지는 않는다.
비파괴적 처리
array.slice(시작 인덱스, 끝 인덱스)
*끝 인덱스: 반환을 원하는 마지막 요소의 인덱스로, 끝 인덱스는 exclusive 하기 때문에 사실상 '가져올 마지막 요소의 인덱스 + 1'이 된다.
let array = [1,2,3,4,5,6,7]
console.log(array.slice(1,5)) // [ 2, 3, 4, 5 ] 1번째 인덱스부터 exclusive한 5번 인덱스인 6을 제외한 4번 인덱스인 5까지
console.log(array) // [1, 2, 3, 4,5, 6, 7]
6. find()
콜백함수의 조건을 충족하는 첫번째로 찾아진 요소를 리턴하는 메소드.
배열의 모든 요소를 순차적으로 돌면서 콜백함수를 호출하다가, 콜백함수에 true를 리턴하는 요소를 찾으면 곧바로 리턴.
조건을 충족하는 요소를 찾지 못했을 경우, undefined를 리턴.
arr.find(callback(value,index,array))
callback은 다음의 세가지 인자를 가지고 호출됩니다: 요소의 값(value), 요소의 인덱스(index), 순회의 대상이 되는 배열(array).
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found); // 12
//find를 활용해 배열에서 객체 찾기
let inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 0}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
let myfruit = inventory.find((fruit) => fruit.quantity === 0) // 화살표 함수 활용
console.log(myfruit) // { name: 'bananas', quantity: 0 } 첫번째로 찾은 객체를 반환
7. some()
배열의 요소 중에서 하나라도 콜백함수의 조건을 충족하는 요소가 있는지 없는지를 검사하는 메소드.
리턴값은 boolean이 된다.
arr.some(callback(value, index, array))
const score = [500,100,400,200,300]
let result = score.some((num) => num > 250) // 배열속에 250보다 큰 숫자가 하나라도 있으면 True를 반환
console.log(result) // true
let scoreSome = score.some((num) => num === 250) // 배열속에 250과 같은 숫자가 하나라도 있으면 true 반환
console.log(scoreSome) // false
8. every()
배열의 모든 요소가 콜백함수의 조건을 충족하는 지 검사하는 메소드.
리턴값은 boolean이 된다.
arr.every(callback(value, index, array))
const score = [500,100,400,200,300]
let result = score.every((num) => num > 250) // 배열속에 모든 요소들이 250을 넘으면 True를 반환
console.log(result) // false
let scoreSome = score.every((num) => num === 250) // 배열속에 모든 요소들이 250과 같으면 True를 반환
console.log(scoreSome) // false
9. reduce()
배열을 돌면서 모든 요소들에 콜백함수를 실행해 누적된 값을 리턴한다.
현재값이 다음 loop에서는 이전값이 되어 전달된다.
즉, 배열을 돌면서 특정 시작점 값에 콜백함수가 실행된 값을 누적해나간다.
원본 배열은 변경하지 않는다.
비파괴적 처리
arr.reduce(콜백함수(이전값, 현재값, 현재인덱스, 배열), 초기값)
const array = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const 시작점 = 0;
const sumArray = array.reduce((sum, curr) => sum + curr,시작점);
console.log(sumArray); // 10
10. sort()
sort() 메소드를 사용하면 배열을 오름차순 혹은 내림차순으로 재정렬 할 수 있다.
파괴적 처리
arr.sort([compareFunction])
const score = [90,88,89,74,75,11,23,9,77]
let up = score.sort((a,b) => a - b); // 오름차순 정렬
console.log(up); // [9, 11, 23, 74, 75, 77, 88, 89, 90]
console.log(score) // [9, 11, 23, 74, 75, 77, 88, 89, 90]
let down = score.sort((a,b) => b - a); // 내림차순 정렬
console.log(down) // [90, 89, 88, 77, 75, 74, 23, 11, 9]
console.log(score) // [90, 89, 88, 77, 75, 74, 23, 11, 9]
11. map()
배열 안의 요소 하나하나에 콜백함수를 실행해 콜백함수에서 가공된 요소들을 새로운 배열로 리턴해주는 메소드.
원본 배열을 변경하지는 않는다.
비파괴적 처리
arr.map(callback(value, index, array))
const array = [1,2,3,4,5]
const map = array.map((value) => value * 2);
console.log(map) // [ 2, 4, 6, 8, 10 ]
12. filter()
콜백함수의 조건을 충족하는 (반환값이 true인)요소들만 모아서 새로운 배열로 리턴해주는 메소드.
원본 배열을 변경하지는 않는다.
비파괴적 처리
arr.filter(callback(element,index,array), thisArg)
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6); //문자열의 길이가 6보다 큰 것만 반환
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
13.forEach()
forEach 메서드는 배열을 반복하는 메서드이다. 일반적으로 무언가를 반복하고자 할때는 for문을 사용한다.
const a = [1,2,3,4,5];
for(let i=0;i<a.length;i++) {
console.log(a[i]); // 출력 : 1,2,3,4,5
}
위와 같이 배열 a의 길이를 이용하여 for 문 안에서 인덱스 i 값을 원소로 하여 반복하는 방식을 사용한다.
하지만 forEach 메서드를 사용하면 보다 쉽게 구현할 수 있다.
const array = ['a', 'b', 'c'];
array.forEach(element => console.log(element));
// a
// b
// c
forEach를 활용하여 객체에 접근하기
const dictArray = [
{'name':"뀨"},
{'name':"쥬"},
{'name':"햅"},
{'name':"끼"},
{'name':'빈'},
{'name':'민'}
]
dictArray.forEach(element => console.log(element.name));
// 뀨
// 쥬
// 햅
// 끼
// 빈
// 민
'JavaScript&TypeScript' 카테고리의 다른 글
JavaScript 회원가입 정규표현식 (0) | 2022.12.21 |
---|---|
파이썬 JS Python Dictionary와 JavaScript Object (0) | 2022.12.16 |
JavaScript 클래스를 알아보자 class (0) | 2022.12.12 |
JavaScript Error handling 에러 핸들 (0) | 2022.12.12 |
Javascript 동기(Sync)&비동기(Async) (0) | 2022.12.12 |
댓글