2020년 5월 10일 일요일

JavaScript built-in array methods

.map ()
.map은 배열의 각 요소를 탐색하고 수정하거나 변환해야 할 때마다 새로운 배열을 반환

1
2
3
4
5
const multiplyByTwo = [467810];
const resultArr = multiplyByTwo.map(element => {
return element * 2;
});
// resultArr = [ 8, 12, 14, 16, 20 ]
cs


.filter()
.filter 메서드는 조건에 따라 배열의 특정 요소를 필터링해야 할 때마다 매우 유용한 방법입니다.
조건의 결과가 True이면 요소가 새 배열에 저장됩니다.
이 메소드는 필터링 된 모든 결과가 포함 된 새 배열을 반환합니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const users = [
{name'Michael', age:30},
{name'Alex', age:19}
{name'John', age:40}
{name'Jackie', age:20}
{name'Melissa', age:25},
{name'Michael', age:30}
]
const filteredUsers = users.filter(person => {
// if the age of the user is more than 20, return this object to the new array.  
return person.age > 20;
});
// the result will be the following
filteredUsers = [ { name'Michael', age: 30 },
  { name'John', age: 40 },
  { name'Melissa', age: 25 },
  { name'Michael', age: 30 } ]
cs

.reduce

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const numbers = [450200758090];
const resultSum = numbers.reduce((accumulator, currentElement) => {
return accumulator + currentElement;
}, 0);
//resultSum = 895
 
 
 
const resultSum = numbers.reduce((accumulator, currentElement) => {
return accumulator + currentElement;
}, 0);
1st Iteration:
accumulator is equal to 0
currentElement = 450
return = (0 + 450= 450 
2nd Iteration:
accumulator is equal to 450
currentElement = 200
return = (200 + 450= 650
....
cs

댓글 없음:

댓글 쓰기