javascript - core - 배열

yj k·2023년 4월 15일

javascript

목록 보기
12/18

배열

01. array

01_array

자바에서 배열은 여러 개의 값을 순차적으로 나열한 자료 구조이다.
자료 타입이 섞여도 상관없다.


생성 방법

1. 배열 리터럴을 통한 생성

// 배열이 가지고 있는 값을 요소라고 부르며 자바스크립트의 "모든 값"은 배열의 요소가 될 수 있다.
const arr = ['바나나', '복숭아', '키위'];
console.log(arr);



2. 배열 생성자 함수

const arr2 = new Array();
console.log(arr2);		// 빈 배열

// 전달 된 인수가 1개이고 숫자인 경우 length 프로퍼티 값이 인수인 배열을 생성
const arr3 = new Array(10);
console.log(arr3);		//<10 empty items>

// 전달 된 인수가 2개 이상이거나 숫자가 아닌 경우 인수를 요소로 갖는 배열 생성
const arr4 = new Array(1, 2, 3);
console.log(arr4);		// [1, 2, 3]



3. Array.of 메소드
Array.of 메소드 : 전달 된 인수를 요소로 갖는 배열 생성

console.log(Array.of(10));
console.log(Array.of(1, 2, 3));
console.log(Array.of("hello", "js"));

// 배열의 요소는 자신의 위치를 나타내는 인덱스를 가지며 배열의 요소에 접근할 때 사용한다
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
// 인덱스 값이 아니라 프로퍼티 키값으로 볼 수 있다.(인덱스처럼 사용되는 것일뿐)


// 배열은 요소의 개수, 즉 배열의 길이를 나타내는 length 프로퍼티를 갖는다
console.log(arr.length);

// for문을 통한 요소 순차 접근
for(let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

// 배열은 별도의 타입이 존재하지 않으며 객체 타입이다.
console.log(typeof arr);		// object




02_differences-from-regular-array(일반적인 배열과의 차이점)

일반적인 배열 : 각 요소가 동일한 데이터 크기를 가지며, 빈틈 없이 연속적으로 이어져 있어
인덱스를 통해 임의의 요소에 한 번에 접근할 수 있는 고속 동작이 장점

자바스크립트의 배열 : 일반적인 배열의 동작을 흉내낸 특수한 객체
각각의 메모리 공간이 동일한 크기를 갖지 않아도 되고 연속적으로 이어져 있지 않을 수도 있다.
인덱스로 배열 요소에 접근하는 경우 일반적인 배열보다 느리지만, 요소의 삽입, 삭제의 경우 빠르다.

//getOwnPropertyDescriptors: 객체의 상세 내용을 볼 수 있다. 
console.log(Object.getOwnPropertyDescriptors([1, 2, 3]));


// 자바스크립트의 모든 값이 객체의 프로퍼티 값이 될 수 있으므로
// 모든 값이 배열의 요소가 될 수 있다.

const arr = [
    '홍길동',
    20,
    true,
    null,
    undefined,
    NaN,
    Infinity,
    [],
    {},
    function() {}
];

console.log(arr);




03_length-property




length property는 요소의 개수를 나타내는 0 이상의 정수의 값을 갖는다.

console.log([].length);
const arr = [1, 2, 3, 4, 5];
console.log(arr.length);




length property 값은 배열에 요소를 추가하거나 삭제하면 자동으로 갱신된다.
push : 요소를 추가하는 메소드
pop : 값을 맨 끝에서부터 꺼내는(삭제) 메소드

arr.push(6);
console.log(arr);
console.log(arr.length);	//[1 2 3 4 5 6]
arr.pop();
console.log(arr);
console.log(arr.length);	//[1 2 3 4 5]




length property에 임의의 숫자 값을 명시적으로 할당할 수 있다.
현재 length보다 작은 숫자 값을 할당하면 배열의 길이가 줄어든다.

arr.length = 3;
console.log(arr);
console.log(arr.length); 	//[1 2 3]




현재 length보다 큰 숫자를 할당하면 length 프로퍼티의 값은 변경 되지만 배열의 길이가 늘어나지는 않는다.

arr.length = 10;
console.log(arr);
console.log(arr.length);	//[1 2 3 <7empty items]
console.log(Object.getOwnPropertyDescriptors(arr));




자바스크립트는 배열의 요소가 연속적으로 위치하지 않고 일부가 비어있는 희소 배열을 문법적으로 허용한다.

const sparse = [, 2, , 4];
console.log(sparse);
console.log(sparse.length);
console.log(Object.getOwnPropertyDescriptors(sparse));




02. array-method

01_array-method(배열 메소드)

Array.prototype은 배열을 위한 빌트인 메서드를 제공한다.

Array.prototype.indexOf

indexOf : 배열에서 요소가 위치한 인덱스를 리턴
lastIndexOf : 배열의 요소가 위치한 마지막 인덱스를 리턴, 인덱스 시작 값을 지정할 수도 있다.

console.log(`foodList.indexOf('물회', 1)

includes : 배열에 해당 요소 포함 여부 리턴

Array.prototype.push : 배열의 맨 뒤에 요소 추가

// 1개씩 추가 
chineseFood.push('양장피');

// 여러개 추가 
chineseFood.push('탕수육', '양장피');

Array.prototype.pop : 배열의 맨 뒤에 요소 제거

Array.prototype.unshift : 배열의 맨 앞에 요소 추가

//하나씩 추가
chickenList.unshift('간장치킨');
chickenList.unshift('마늘치킨');
//결과 : [마늘치킨, 간장치킨]

// 여러개 추가
chickenList.unshift('간장치킨', '마늘치킨');
//결과 : [간장치킨, 마늘치킨]

//순서가 달라질 수 있다.

Array.prototype.shift : 배열의 맨 앞 요소 제거 후 반환

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

//배열명.concat(배열명1, 배열명2, ...)
const idol1 = ['아이브', '오마이걸'];
const idol2 = ['트와이스', '에스파'];
const idol3 = ['블랙핑크', '레드벨벳'];


// 배열명.concat(배열명1, 배열명2, ...)
const mix = idol1.concat(idol2);
const mix2 = idol3.concat(idol1, idol2);

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

Array.prototype.slice : 배열의 요소 선택 잘라내기
(실제 원본 배열을 바꾸지는 않는다. 그 값을 꺼내서 사용할 수 있는 것)

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

Array.prototype.splice : 배열의 index 위치의 요소 제거 및 추가
(실제 원본 배열에 영향을 준다.)

console.log(`front.splice(3, 1, "React") : ${front.splice(3, 1, "React")}`);    // jQuery
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




02_array-higher-order-function(배열 고차 함수)


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


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

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

// 숫자 오름차순 정렬
function compare(a,b) {

	//	compare 함수는 직접 정의
    if(a > b) return 1;
    if(a == b) return 0;
    if(a < b) return -1;
}


numbers.sort(compare);
console.log('매개변수로 compare 함수 전달하여 숫자 오름차순 정렬');
console.log(numbers);

// 숫자 내림차순 정렬
numbers.sort(function(a, b) { return b - a; });
numbers.sort((a, b) => b - a);

console.log('숫자 내림차순 정렬');
console.log(numbers);




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(`index : ${index}`);
    console.log(`array : ${array}`);
});

// 매개변수 item, index, array 전부 쓰지 않고, 필요한 것만 적어도된다.
// 아예 쓰지 않아도된다.
// numbers[0]의 값(item)과 인덱스(index)와 배열의 내용(array)을 출력해준다.

// 각 요소 별로 * 10 한 값을 콘솔에 출력
// item 안에 있는 값에 10씩 곱해준다 numbers.forEach(item => console.log(item * 10));

Array.prototype.`map` : 배열 요소 전체를 대상으로 콜백 함수 호출 후 반환 값들로 구성 된 새로운 배열 반환 ``` // 사용법 배열.map(function(item, index, array){ // 배열 요소 각각에 반환할 새로운 값 }); ```
``` const types = [true, 1, 'text'].map(item => typeof 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]


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

const odds = numbers.filter(item => item % 2);
console.log(odds); // 홀수에 해당하는 값만 반환되는 배열을 반환


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

**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});
});

// 합산
const sum = numbers.reduce(function(previousValue, currentValue){
return previousValue + currentValue;
});
console.log(sum : ${sum}); //15

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


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

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


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

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


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

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

result = students.find(item => item.name === '유관순');
console.log(result);
result = students.findIndex(item => item.name === '유관순');
console.log(result);

result = students.find(item => item.name === '신사임당');
console.log(result);
result = students.findIndex(item => item.name === '신사임당');
console.log(result);

find, findIndex는 일치하는 요소를 찾으면 더 이상 탐색하지 않고 하나의 요소, 인덱스만 반환한다.
만약 60점 이상인 학생들을 찾고 싶다면?
filter는 콜백함수의 실행 결과가 true인 배열 요소의 값만을 추출한 새로운 배열을 반환한다.

result = students.filter(item => item.score >= 80);
console.log(result);

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

0개의 댓글