LECTURE/JavaScript

Array method - 배열 메소드, 배열 고차 함수

heywoo 2023. 2. 9. 22:25
배열 메소드
// 배열의 생성자 함수는 Array
console.log(arr.constructor === Array);   // true

// 배열의 프로토타입 객체는 Array.prototype -> 이 안에 constructor가 있고 arr는 Array.prototype을 상속한다.
console.log(Object.getPrototypeOf(arr) === Array.prototype);  // true
// => Array.prototype은 배열을 위한 빌트인 메서드를 제공한다.

 

Array.prototype.indexOf
  •  indexOf : 배열에서 요소가 위치한 인덱스를 리턴
  •  lastIndexOf : 배열의 요소가 위치한 마지막 인덱스를 리턴
  •  includes : 배열에 해당 요소 포함 여부 리턴
const foodList = ['물회', '삼계탕', '냉면', '수박', '물회'];

console.log(`foodList.indexOf('물회') : ${foodList.indexOf('물회')}`);            // 0
console.log(`foodList.indexOf('물회', 1) : ${foodList.indexOf('물회', 1)}`);      // 1번 인덱스부터 시작 4
console.log(`foodList.indexOf('삼겹살') :  ${foodList.indexOf('삼겹살')}`);             
// -1  인덱스로서 존재할 수 없는 숫자로 '찾지 못했다'는 걸 의미

console.log(`foodList.lastIndexOf('물회') : ${foodList.lastIndexOf('물회')}`);       // 4
console.log(`foodList.lastIndexOf('물회', 1) : ${foodList.lastIndexOf('물회', 1)}`);   
// 0  1번인덱스부터 0번쪽으로 읽는다
console.log(`foodList.lastIndexOf('삼겹살') : ${foodList.lastIndexOf('삼겹살')}`);   // -1

console.log(`foodList.includes('물회') : ${foodList.includes('물회')}`);             // true
console.log(`foodList.includes('삼겹살') : ${foodList.includes('삼겹살')}`);         // false

 

 
Array.prototype.push : 배열의 맨 뒤에 요소 추가
Array.prototype.pop : 배열의 맨 뒤에 요소 제거
const chineseFood= ['짜장면', '짬뽕', '우동'];

console.log(`push 전 chineseFood : ${chineseFood}`);            // 짜장면,짬뽕,우동

chineseFood.push('탕수육');
chineseFood.push('양장피');
// chineseFood.push('탕수육', '양장피');

console.log(`push 후 arr :  ${chineseFood}`);                   // 짜장면,짬뽕,우동,탕수육,양장피

console.log(`chineseFood.pop() : ${chineseFood.pop()}`);        // 양장피
console.log(`chineseFood.pop() : ${chineseFood.pop()}`);        // 탕수육
console.log(`chineseFood.pop() : ${chineseFood.pop()}`);        // 우동

console.log(`pop 후 chineseFood :  ${chineseFood}`);            // 짜장면,짬뽕

 

 
Array.prototype.unshift : 배열의 맨 앞에 요소 추가
Array.prototype.shift : 배열의 맨 앞 요소 제거 후 그 요소를 반환
const chickenList = ['양념치킨', '후라이드', '파닭'];

console.log(`unshift 전 chickenList : ${chickenList}`);         // 양념치킨,후라이드,파닭

chickenList.unshift('간장치킨');
chickenList.unshift('마늘치킨');
// chickenList.unshift('간장치킨', '마늘치킨'); -> 이 경우 이 덩어리 그대로 앞에 추가됨

console.log(`unshift 후 chickenList : ${chickenList}`);         // 마늘치킨,간장치킨,양념치킨,후라이드,파닭

console.log(`chickenList.shift() : ${chickenList.shift()}`);    // 마늘치킨
console.log(`chickenList.shift() : ${chickenList.shift()}`);    // 간장치킨
console.log(`chickenList.shift() : ${chickenList.shift()}`);    // 양념치킨

console.log(`shift 후 chickenList : ${chickenList}`);           // 후라이드,파닭

 

Array.prototype.concat : 두 개 이상의 배열을 결합

const idol1 = ['아이브', '오마이걸'];
const idol2 = ['트와이스', '에스파'];
const idol3 = ['블랙핑크', '레드벨벳'];

// 배열명.concat(배열명1, 배열명2, ...)
const mix = idol1.concat(idol2);   // 나열된 순서대로 결합한다. 1+2
const mix2 = idol3.concat(idol1, idol2);  // 3+1+2

console.log(`idol1 기준으로 idol2 배열을 concat : ${mix}`);            // 아이브,오마이걸,트와이스,에스파
console.log(`idol3 기준으로 idol1, idol2 배열을 concat : ${mix2}`);    
// 블랙핑크,레드벨벳,아이브,오마이걸,트와이스,에스파

 

Array.prototype.slice : 배열의 요소 선택 잘라내기, 원본 배열은 변경하지 않는다.

Array.prototype.splice : 배열의 index 위치의 요소 제거 및 추가, 원본 배열을 변경한다.

const front = ['HTML', 'CSS', 'JavaScript', 'jQuery'];

// slice(시작인덱스, 종료인덱스->그 인덱스 앞에서 자른다)
console.log(`front.slice(1, 3) : ${front.slice(1, 3)}`);                     // CSS,JavaScript
console.log(`front : ${front}`);                                             // HTML,CSS,JavaScript,jQuery

// splice(index, 제거수, 추가값1, 추가값2, ...)
console.log(`front.splice(3, 1, "React") : ${front.splice(3, 1, "React")}`);    
//jQuery  3번인덱스부터 요소 1개를 제거하고 React를 추가한다.
console.log(`front : ${front}`);                                             // HTML,CSS,JavaScript,React

 

Array.prototype.join : 배열을 구분자로 결합하여 문자열로 반환

const snackList = ['사탕', '초콜렛', '껌', '과자'];
console.log(`snackList.join() : ${snackList.join()}`);         // 구분자를 안 쓰면 컴마->사탕,초콜렛,껌,과자
console.log(`snackList.join('/') : ${snackList.join('/')}`);   // 사탕/초콜렛/껌/과자

 

Array.prototype.reverse : : 배열의 순서를 뒤집는다. 원본도 바뀜.

console.log(`[1, 2, 3, 4, 5].reverse() : ${[1, 2, 3, 4, 5].reverse()}`);  
// 5,4,3,2,1

 

배열 고차 함수

고차 함수 : 함수를 인수로 전달받거나 함수를 반환하는 함수

Array.prototype.sort : 배열을 정렬 기준으로 정렬

et numbers = [];

for(let i = 0; i < 10; i++) {
    numbers[i] = Math.floor(Math.random() * 100 ) + 1;
}

//floor 로 내림처리

console.log(`정렬 전 numbers : ${numbers}`);
//정렬 전 numbers : 11,29,22,76,97,68,13,7,14,61

// 오름차순 정렬이 기본이며 정렬 후 정렬 순서를 유지한다. 
numbers.sort();
console.log(`정렬 후 numbers. : ${numbers}`);
//정렬 후 numbers. : 11,13,14,22,29,61,68,7,76,97

배열은 기본적으로 문자열 정렬이 되므로 한자리수, 세자리수가 올바르지 않게 정렬되는 모습을 보임
 => 다른 정렬 기준을 사용하려면 compare 함수를 인수로 전달해야 함

// 숫자 오름차순 정렬
function compare(a, b) {  
    if(a > b) return 1; // 양수면 위치를 바꾼다
    if(a == b) return 0;
    if(a < b) return -1;
}
//compare는 콜백함수 sort는 고차함수이다.
numbers.sort(compare);
console.log(numbers);
//출력
[
   7, 11, 13, 14, 22,
  29, 61, 68, 76, 97
]



// 숫자 내림차순 정렬
numbers.sort(function(a, b) { return b - a;});  
// b - a가 양수, 뒤에 자리가 더 크면 자리를 바꾼다 -> 내림차순
numbers.sort((a, b) => b - a);
console.log(numbers);

//출력
[
  97, 76, 68, 61, 29,
  22, 14, 13, 11,  7
]

 

Array.prototype.forEach : for를 대체할 수 있는 고차함수

배열.forEach(function(item, index, array){
        
    });

함수 몸체에 배열 요소 각각에 실행할 기능을 작성하며, 요소만 반복해도 된다.

numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(item, index, array){
    console.log(`item : ${item}`);
    console.log(`item : ${index}`);
    console.log(`item : ${array}`);
}); //item : 요소 , array는 배열 전체

//출력

item : 1
item : 0
item : 1,2,3,4,5
item : 2
item : 1
item : 1,2,3,4,5
item : 3
item : 2
item : 1,2,3,4,5
item : 4
item : 3
item : 1,2,3,4,5
item : 5
item : 4
item : 1,2,3,4,5




// 각 요소 별로 * 10 한 값을 콘솔에 출력
numbers.forEach(item => console.log(item * 10));
//출력
10
20
30
40
50

 

Array.property.map : 배열 요소 전체를 대상으로 콜백 함수 호출 후 반환 값들로 구성된 새로운 배열 반환

배열.map(function(item, index, array){
        
    })

함수 몸체에 배열 요소 각각에 반환할 새로운 값을 작성한다.

const types = [true, 1, 'text'].map(item => typeof item); //item의 테이터 타입을 반환해라
console.log(types);
//[ 'boolean', 'number', 'string' ]

const lengths = ['apple', 'banana', 'cat', 'dog', 'egg'].map(item => item.length);
console.log(lengths);
//[ 5, 6, 3, 3, 3 ]

 

Array.prototype.filter : 배열 요소 전체를 대상으로 콜백 함수 호출 후 반환 값이 true인 요소로만 구성된 새로운 배열 반환

const odds = numbers.filter(item => item % 2); //2로 나누었을때 몫이 있는 요소 반환
console.log(odds);
//[ 1, 3, 5 ]

 

Array.prototype.reduce : 배열을 순회하며 각 요소에 대하여 이전의 콜백 함수 실행 반환값을 전달하여 콜백함수를 실행하고 그 결과를 반환

=>reduce 함수는 배열의 요소를 순차적으로 순회하면서 리듀서(reducer) 함수를 실행하고 하나의 결과값을 반환

arr.reduce((accumulator, currentValue, index, array) => {

}, initialValue);

- accumulator : 누산기 순회하면서 계속 더해져서 합쳐지는 값
- initialValue Optional : callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 
초기값을 제공하지 않으면 배열의 첫 번째 요소가 previousValue로 선언되고 두 번째 요소가 currentValue로 선언된다.
- 리턴 값 : 누적 계산의 결과값
  •     previousValue : 이전 콜백의 반환 값
  •     currentValue : 배열 요소의 값
  •     currentIndex : 인덱스
  •     array : 메소드를 호출한 배열
numbers.reduce(function(previousValue, currentValue, currentIndex, array){
        console.log(`previousValue : ${previousValue}`);
        console.log(`currentValue : ${currentValue}`);
        console.log(`currentIndex : ${currentIndex}`);
        console.log(`array : ${array}`);
    })
    
    
    //출력
previousValue : 1
currentValue : 2
currentIndex : 1
array : 1,2,3,4,5
previousValue : undefined  //콜백을 한번만 해서?
currentValue : 3
currentIndex : 2
array : 1,2,3,4,5
previousValue : undefined
currentValue : 4
currentIndex : 3
array : 1,2,3,4,5
previousValue : undefined
currentValue : 5
currentIndex : 4
array : 1,2,3,4,5
// 합산
    const sum = numbers.reduce(function(previousValue, currentValue){
        return previousValue + currentValue;  //연산결과를 누산기, previousValue에 넣어 최종값을 얻는다.
    });
    console.log(`sum : ${sum}`)   // 1+2 = 3, 3+3 = 6 6+4 =10 10+5 =15


//최대값 취득
    const max = numbers.reduce(function(pre, cur) {
        return pre > cur ? pre : cur;   // 1 < 2 , 2 < 3, 3 < 4, 4 < 5
    });
    console.log(`max : ${max}`); //5

 

Array. prototype.some : 배열 내 일부 요소가 콜백 함수의 테스트를 통화하는지 확인하여 그 결과를 boolean으로 반환

// 배열 내 요소 중 10보다 큰 값이 1개 이상 존재하는지 확인
let result = [1, 5, 3, 2, 4].some(item => item > 10);
console.log(`result : ${result}`);  // false

// 배열 내 요소 중 3다 큰 값이 1개 이상 존재하는지 확인
 result = [1, 5, 3, 2, 4].some(item => item > 3);
console.log(`result : ${result}`);  //true

 

Array.prototype.every : 배열 내 모든 요소가 콜백 함수의 테스트를 통화하는지 확인하여 그 결과를 boolean으로 반환

// 배열 내 모든 값이 3보다 큰지 확인
result = [1, 5, 3, 2, 4].every(item => item > 3);
console.log(`result : ${result}`);  //false

// 배열 내 모든 값이 0보다 큰지 확인
result = [1, 5, 3, 2, 4].every(item => item > 0);
console.log(`result : ${result}`);  //ture

 

Arrays.prototype.find : 배열을 순회하며 각 요소에 대하여 인자로 주어진 콜백 함수를 실행하여 그 결과가 참인 첫번째 요소를 반환. 참인 요소가 존재하지 않다면 undefinded 반환

Arrays.prototype.findIndex : 배열을 순회하며 각 요소에 대하여 인자로 주어진 콜백 함수를 실행하여 그 결과가 참인 첫번째 요소의 인덱스를 반환. 참인 요소가 존재하지 않다면 -1 반환

 

const student = [
    { name : '유관순', score : 90},
    { name : '홍길동', score : 80},
    { name : '장보고', score : 70}
];

result = student.find(item => item.name == '유관순');
console.log(result);									//{ name: '유관순', score: 90 }
result = student.findIndex(item => item.name == '유관순');
console.log(result);									//0

result = student.find(item => item.name == '신사임당');
console.log(result);									//undefined
result = student.findIndex(item => item.name == '신사임당');
console.log(result);									//-1

// find, findIndex는 일치하는 요소를 찾으면 더 이상 탐색하지 않고 하나의 요소, 인덱스만 반환한다.

 

Array.property.filter : filter는 콜백함수의 실행 결과가 true인 배열 요소의 값만을 추출한 새로운 배열을 반환한다.

// 만약 80점 이상인 학생들만 찾고 싶다면?
result = student.filter(item => item.score >= 80);
console.log(result); 
//[ { name: '유관순', score: 90 }, { name: '홍길동', score: 80 } ]

result = student.find(item => item.score >= 80);
console.log(result);
// 첫 번째 요소인 유관순만 반환한다. { name: '유관순', score: 90 }

// 만약 80점 이상인 학생들만 찾고 싶다면?
result = student.filter(item => item.score >= 80);
console.log(result); // 유관순 하나만 반환한다.

result = student.find(item => item.score >= 80);
console.log(result);