본문 바로가기

Programing/JavaScript

[JavaScript] 배열 유용 Array.prototype.forEach() // Array.prototype.map() // Array.prototype.reduce() // Array.prototype.join()

arr.forEach(callback) Immutable (불변)

· arguments : element의 길이만큼 반복하는 함수

  - parameters

    순서대로 (현재 element, 현재 index, 배열 그 자체)

· return value : 없음 

· element 마다 함수를 반복 실행 한다.

· callback에다가 함수를 넣으면됨

 

1
2
3
4
5
6
7
8
9
10
11
function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}
 
// 인덱스 2는 배열의 그 위치에 항목이 없기에
// 건너뜀을 주의하세요.
[25, , 9].forEach(logArrayElements);
// 기록:
// a[0] = 2
// a[1] = 5
// a[3] = 9
cs

 

 

 

arr.map(callback) Immutable

· argument : element의 길이만큼 반복하는 함수

    - parameters

      순서대로 (현재element, 현재index, 배열그자체)

· return value : callback이 실행되면서 return하는 값들을 모은 새로운 배열

· callback 내에서 return필요

· 기존배열과 동일한 길이를 갖고, 형태가 다른 새로운 배열을 만들 때 유용

 

1
2
3
4
5
[134].map(function(currentElement, index, array) {
    return currentElement * 2;
});
 
//[2, 6, 10]
cs

 

 

 

arr.reduce(callback함수[, initialValue초기값]) / Immutable

MDN문서

· arguments : element의 길이만큼 반복하는 함수, 초기값(있어도되고 없어도되고)

  - parameters

  순서대로 (누적값 accumulator, 현재값 currentValue, 현재 index currentIndex, 원본배열)

· return value : 최종 누적값

· 모든 element의 계산을 누적해 하나의 결과를 리턴할 때 유용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 요소를 누적하여 더하는 값
[1234].reduce(function(accmulator, element) {
    return accmulator + element;
}, 0/*초기값*/);
// return 10
// 초기값이 10 이라면 10부터 시작해서 더해지는 것
 
 
// 길이만큼 1씩더하기
[3456].reduce(function(acc, element) {
    return acc + 1;
}, 0);
// return 4
 
 
//문자 합치기
['code''states'].reduce(function(acc,element) {
    return acc + element;
}, '')
// return "codestates"
 
 
 
//화살표함수 사용 =>
const array1 = [1234];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
 
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
 
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
 
cs

 

 

* 관련문제

 

Write a function called "getLongestElement".

 

Given an array, "getLongestElement" returns the longest string in the given array.

 

Notes:

* If there are ties, it returns the first element to appear.

* If the array is empty, tt should return an empty string.

 

→ 배열안에서 가장 문자열 길이가 긴 요소 출력하기

 

1
2
3
4
//예문
 
var output = getLongestElement(['one''two''three']);
console.log(output); // --> 'three'
cs

 

 

답 :

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function getLongestElement(arr) {
  if(Array.isArray(arr) && arr.length === 0) {
    return "";     // 배열이 비어있을 경우 "" 리턴
  }
  
  return arr.reduce((accu,elem) => {     //reduce 값을 출력하려면
    if(accu.length >= elem.length) {     //앞에 return을 꼭 써줄것 !!!
      return accu;
    } else {
      return elem;
    }
    
  });
  
}
 
var output = getLongestElement(['one''two''three']);
console.log(output); // --> 'three'
cs

 

 

 

다른 예문 :

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function findSmallestElement(arr) {
    var shortest = 0;
    if (arr.length !== 0) {
        shortest = arr.reduce(function(a, b) {
            if (a < b) {
                return a;
            } else {
                return b;
            }
        });
    }
    return shortest;     // 변수 안에 값을 넣어 반환할 수 있다
}
 
var output = findSmallestElement([41910]);
console.log(output); // --> 1
cs

 

 

 

Array.prototype.join()  / Immutable


1
2
3
4
5
6
7
8
9
10
11
12
13
14
var elements = ['Fire''Wind''Rain'];
 
var joinElem = elements.join();
console.log(joinElem);
// expected output: Fire,Wind,Rain
 
console.log(elements.join());
// expected output: Fire,Wind,Rain
 
console.log(elements.join(''));
// expected output: FireWindRain
 
console.log(elements.join('-'));
// expected output: Fire-Wind-Rain
 
cs

 

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

 

 

+ join() 헷갈렸던 부분

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
console.log(Array(5));
// Array [undefined, undefined, undefined, undefined, undefined]
// Array(num) ==> Array의 num만큼 빈 배열을 만들어낸다
 
 
var result = Array(5).join(" " + "Brain");
console.log(result);
// " Brain Brain Brain Brain"
// " " + "Brain" => " Brain" / " Brain"을 빈 배열 5칸 사이에 join한 것
// 그래서 " Brain"이 4번 나오는 것
 
 
var joinAStr = Array(5).join("A")
console.log(joinAStr);
// "AAAA"
 
 
 
var elements = ['Fire''Wind''Rain'];
console.log(elements.join(' (Plus!) '));
// "Fire (Plus!) Wind (Plus!) Rain"
// 배열 값 사이마다 join하기 때문에 (Plus!)는 두번 나왔다
cs

 

 

* 관련 문제

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var meglomaniac = {
  mastermind : "Brain",
  henchman: "Pinky",
  battleCry: function (noOfBrains) {
     return "They are " + this.henchman + " and the" +
        Array(noOfBrains + 1).join(" " + this.mastermind);
  }
};
 
var battleCry = meglomaniac.battleCry(4);
expect("They are Pinky and the Brain Brain Brain Brain").toMatch(battleCry);
 
/* expect("They are Pinky and the Brain Brain Brain Brain").toMatch(battleCry);
는 battleCry 값은 "They are Pinky and the Brain Brain Brain Brain" << 이렇게 나온다
cs

 

 

 

Array.prototype.reverse() / mutable

1
2
3
4
5
6
7
8
9
10
11
12
13
var array1 = ['one''two''three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']
 
var reversed = array1.reverse(); 
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']
 
/* Careful: reverse is destructive. It also changes
the original array */ 
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']
 
cs

 

배열의 순서를 역순으로 원본이 변한다 역순으로

 

 

 

Array.prototype.sort()

abc, 123순으로 길이에 상관없이 맨앞에 나온 것을 기준으로 정렬

 

 

 

1
2
3
4
5
6
7
8
9
10
11
var months = ['March''Jan''Feb''Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
 
var array1 = [130421];
array1.sort();
console.log(array1.sort()); // return value : Array [1, 21, 30, 4]
console.log(array1);
// expected output: Array [1, 21, 30, 4]
 
cs

 

 

 

 

 

Array.prototype.fill()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//arr. fill ( value [ , start [ , end]] )
 
var array1 = [1234];
 
// fill with 0 from position 2 until position 4
console.log(array1.fill(024));
// expected output: [1, 2, 0, 0]
 
// fill with 5 from position 1
console.log(array1.fill(51));
// expected output: [1, 5, 5, 5]
 
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
 
cs