4 minute read

배열

  • 여러개의 항목이 들어있는 리스트
  • 길이가 가변적!
  • 다양한 자료형, 함수, 객체, 배열 모두 들어갈 수 있음
  • 자바처럼 인덱스 0부터 시작하고, 인덱스로 각 요소를 접근할 수 있음

[Usage]

const 혹은 let 배열이름=[값];

const array=[1,2,3,4,5,'김치전',5.1,
{
    name:'홍길동',
    age:26
}, 
function(){
    console.log('안녕하십니까~');
}];

console.log(array[7]);//{name: "홍길동", age: 26}
console.log(array[8]());//안녕하십니까~

배열.push(값)

  • 배열의 내장함수로, 값을 추가하는 기능

위의 배열을 그대로 이용해보자!

array.push(`피자는 항상 맛있지! 당연한 말씀을~`);
console.log(array[9]);//피자는 항상 맛있지! 당연한 말씀을~

배열.length

  • 배열 내부의 내장된 값으로써, 배열의 길이를 반환해줌
console.log(array.length);//10

배열의 내장함수(push는 위에서 언급했으므로 생략)

배열.forEach(함수)

  • 배열에 대해서 각 인덱스에 대해서 함수를 실행

.

const heroes=[
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
];

function print(hero){
    console.log(hero);
}

heroes.forEach(print);
/**
 * 아이언맨
 * 캡틴 아메리카
 * 토르
 * 닥터 스트레인지
 */
//같은 결과!(익명함수)
heroes.forEach(function(hero){
     console.log(hero);
 });
 /**
 * 아이언맨
 * 캡틴 아메리카
 * 토르
 * 닥터 스트레인지
 */
//같은 결과인데 화살표 함수를 이용!
console.log("---");
heroes.forEach((hero)=>console.log(hero));
console.log("---");
heroes.forEach(hero=>{console.log(hero)});

배열명.map(함수)

  • 배열 내의 원소를 특정 형태로 변환

배열명.map(형태로 바꾸기 위한 함수);

—원 배열인 arr의 각 요소에 대해서 제곱한 값을 반환하기

const arr = [1,2,3,4,5,6,7,8,9];
const squared = arr.map((i)=>(i*i));
console.log(squared);
//1 4 9 16 25 36 49 64 81

— 객체 배열에서 text 요소로만 이루어진 배열을 뽑아내기

const items=[
    {
        id : 1,
        text:'hello'
    },
    {
        id : 2,
        text:'hihi'
    }
];
//text로만 이루어진 문자열 배열로 만들기
const text=items.map((i)=>(i.text));
console.log(text);
//hello hihi

배열에서 어떤 위치에 있는지 알 수 있는 함수

  1. 배열명.indexOf(값)
    • 어떤 값이 몇 번째 인덱스에 있는지 반환해줌
    • 일치하는 것이 없으면 -1 반환
const heroes=[
    '아이언맨',
    '캡틴 아메리카',
    '토르',
    '닥터 스트레인지'
];
//indexOf : 인덱스 알아내기
const idx = heroes.indexOf('토르');
console.log(idx);//2
  1. 배열명.findIndex(함수)
  • 값이 객체이거나 특정 조건(예시 : 특정값을 나누었을때 나머지가 2인 경우)일 때, indexOf로는 찾기 힘들기 때문에 이때 사용!
  • 못찾으면 -1 반환
  • 가장 첫번째로 찾은 경우를 choice하여 알려줌

— id,text, done을 필드로 갖는 객체들의 배열에서 id가 3일 때의 인덱스 구하기

const toDos=[
    {
        id:1,
        text:'자바스크립트 입문',
        done:true
    },
    {
        id:2,
        text:'함수 배우기',
        done:true
    },
    {
        id:3,
        text:'객체와 배열 배우기',
        done:true
    },
    {
        id:4,
        text:'배열 내장함수 배우기',
        done:false
    }
];

const objIdx = toDos.findIndex((toDo)=>(toDo.id===3));
console.log(objIdx);
  1. 배열명.find(함수)
  • findIndex와 비슷하지만, 해당되는 객체/원소 자체를 반환해줌
  • 가장 첫번째로 찾은 경우를 choice하여 알려줌
const toDos=[
    {
        id:1,
        text:'자바스크립트 입문',
        done:true
    },
    {
        id:2,
        text:'함수 배우기',
        done:true
    },
    {
        id:3,
        text:'객체와 배열 배우기',
        done:true
    },
    {
        id:4,
        text:'배열 내장함수 배우기',
        done:false
    }
];

const fIdx = toDos.find((toDo)=>(toDo.done===false));
console.log(fIdx);//{id: 4, text: "배열 내장함수 배우기", done: false}

배열명.filter(함수)

  • 특정 조건을 만족하는 요소들을 모아서 새로운 배열로 반환
const tasksDone = toDos.filter((toDo)=>(toDo.done===true));
//const tasksDone = toDos.filter((toDo)=>(toDo.done));
console.log(tasksDone);

const tasksNotDone = toDos.filter((toDo)=>(toDo.done===false));
//const tasksNotDone = toDos.filter((toDo)=>(!toDo.done));
console.log(tasksNotDone);

https://github.com/hy6219/TIL-Today-I-Learned-/blob/main/FE/Javascript/%EB%B0%B0%EC%97%B4%20%EB%82%B4%EC%9E%A5%20%ED%95%A8%EC%88%98%20filter.PNG?raw=true

배열 내장 함수 filter

배열명.splice(제거할 요소의 인덱스, 갯수)

  • 배열에서 특정 항목을 제거
  • 제거하는 과정에서 몇 번째 요소인지 명시해주어야 함

[USAGE]

배열명.splice(인덱스, 인덱스로부터 제거할 요소 갯수)
const numbers=[10,20,30,40];
const idx = numbers.indexOf(30);
const spliced= numbers.splice(idx,2);
console.log(spliced);//[30, 40] - 제거된 요소들
console.log(numbers);// [10, 20] - 제거되고 남은 요소들

배열명. slice(시작인덱스, 끝나는 인덱스)

  • splice와 기능적으로는 동일하나,

1) 원본 배열을 훼손하지 않는다는 점(splice는 원본 배열을 훼손! 변경!)

2) [시작,끝)까지 잘라내고, 이 각각을 매개변수로 한다는 점

에서 다르다!

[USAGE]

배열명.slice(시작인덱스, 끝나는 인덱스)
const numbers=[10,20,30,40];

const sliced= numbers.slice(0,2);
console.log(sliced);// [10, 20]
console.log(numbers);//[10, 20, 30, 40]

배열명.shift()

  • 첫 번째 원소를 배열에서 추출해줌
  • 기존 배열을 훼손함!
  • 모두 꺼내진 다음에는 shift된 원소를 담는 공간(아래의 경우 value)에서는 undefined 를 반환
  • 비어있을 때까지 실행하는데, 모두 비어있는 시점부터 그 이후(원 배열의 크기보다 더 많이 shift하는 경우)는 [] (빈 배열)을 반환

[USAGE]

배열명.shift();

const numbers=[10,20,30,40];

let value=numbers.shift();
console.log(value);//10
console.log(numbers);//[20, 30, 40]

배열명.pop()

  • 마지막 원소부터 배열에서 추출
  • 원 배열을 훼손함
  • 모두 꺼내고 나면 원 배열은 계속 []를 반환하고,
  • 모두 꺼내진 다음에는 pop된 원소를 담는 변수에서는 undefined 를 반환
const numbers=[10,20,30,40];
let val = numbers.pop();
console.log(val);//40
console.log(numbers);//[10, 20, 30]

배열명.unshift(값)

  • 배열의 첫 번째 요소에 값을 추가
  • (push, pop), (shift,unshift)로 사용할 때 짝을 지어서 사용!
  • unshift를 사용할 때 그 값을 담아서 확인해보면 추가한 후의 배열의 크기를 확인할 수 있음
  • 원 배열을 훼손함
const numbers=[10,20,30,40];

let value = numbers.unshift('혹시 홍길동?');
console.log(value);//배열의 길이 5를 반환
console.log(numbers);//["혹시 홍길동?", 10, 20, 30, 40]

배열명.concat(배열명)

  • 여러 개의 배열을 합쳐서 하나의 배열로 만들어줌
  • 기존 배열을 건드리지 않고, 새로운 배열을 만듦
  • join 내장함수와 혼동될 수 있음-join은 배열을 문자열로 구분자를 이용해서 만들어줌
const arr1 = [1,2,3];
const arr2 = [4,5,6];

const concated = arr1.concat(arr2);
console.log(concated);//[1, 2, 3, 4, 5, 6]

//spread 연산자를 이용해서 같은 결과를 낼 수도 있음
const spread=[...arr1, ...arr2];
console.log(spread);//[1, 2, 3, 4, 5, 6]
const arr =[1,2,3,4,5];
console.log(arr.join());//1,2,3,4,5
console.log(arr.join(' '));//1 2 3 4 5

배열명.reduce(callback[, initialValue])

  • 배열안에 있는 요소를 이용해서 연산할 때 사용됨
  • callback : 배열의 각 요소에 대해서 실행할 함수(아래의 네 가지 인수를 받을 수 있음)
    1. accumulator : 누산기! 함수에 따라서 처리되는 값을 저장함
    2. currentValue : 처리할 현재 요소
    3. currentIndex(선택! 필수 ❌) : 처리할 현재 요소의 인덱스
    4. array(선택! 필수 ❌) : reduce()를 호출할 배열! 자기자신!
  • initialValue(선택! 필수 ❌) : callback의 최초 호출에서 첫 번째 인수에 제공하는 값! initialValue를 제공하지 않으면 배열의 첫 번째 요소를 사용 -initialValue가 들어가면 initialValue 다음에 배열의 각 요소가 대입될 것!
const numbers=[1,2,3,4,5];

let sum = numbers.reduce((accumulator,currentValue)=>(accumulator+currentValue));
console.log(sum);//15

sum = numbers.reduce((accumulator,currentValue)=>(accumulator*currentValue));
console.log(sum);//120

sum = numbers.reduce((accumulator,currentValue)=>(accumulator+currentValue),5);
console.log(sum);//20

//평균 구하기
let avg= numbers.reduce((accumulator,current,index,array)=>{
    if(index===array.length-1){
        //인덱스가 마지막 인덱스라면
        return (accumulator+current)/array.length;
    }
    return (accumulator+current);
},0);

console.log(`평균: ${avg}`);//평균: 3

Updated: