(JavaScript) Array function

자주 까먹는데 자주 쓰는,,,

push()

직접 Array 끝에 값을 추가

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.push('zlcus')); // 추가 이후 개수 출력
console.log(arraySample);

result

9
[
  'A',     'B',
  'C',     'D',
  'E',     'F',
  'G',     'H',
  'zlcus'
]

pop()

Array 값을 끝에서 가져오고 삭제

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.pop()); // 마지막 인덱스 값을 반환 후 삭제
console.log(arraySample);

result

H
[
  'A', 'B', 'C',
  'D', 'E', 'F',
  'G'
]

shift()

Array 값을 앞에서 가져오고 삭제

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.shift()); // 첫번째 인덱스 값을 반환 후 삭제
console.log(arraySample);

result

A
[
  'B', 'C', 'D',
  'E', 'F', 'G',
  'H'
]

unshift()

직접 Array 앞에 값을 추가

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.unshift('coco')); // 추가 이후 개수 출력
console.log(arraySample);

result

9
[
  'coco', 'A', 'B',
  'C',    'D', 'E',
  'F',    'G', 'H'
]

splice()

Array의 특정 위치에 값을 추가하거나 삭제

code

let exampleArry = ['A', 'B', 'C', 'D', 'E'];

console.log(exampleArry.splice(0, 3)); // 0번째 인덱스부터 3개를 삭제하고 삭제된 값 반환
console.log(exampleArry.splice(0, 0)); // 이건 삭제 안하는 것
console.log(exampleArry);
for(let i in exampleArry){
    console.log(`${i} : ${exampleArry[i]}`); // 인덱스가 누락되지는 않음
}
console.log(exampleArry.splice(0, 0, 'a', 'b', 'c')); // 0번째 인덱스부터 0개를 삭제하고 추가
console.log(exampleArry);

result

[ 'A', 'B', 'C' ]
[]
[ 'D', 'E' ]
0 : D
1 : E
[]
[ 'a', 'b', 'c', 'D', 'E' ]

concat()

Array 끝에 추가 이후 Array를 반환, 원본 Array는 변하지 않음

code

let concatExample = ['A', 'B'];
console.log(concatExample.concat('C')); 

const concatExample2 = ['D', 'E'];
console.log(concatExample.concat(concatExample2));

console.log(`concatExample: ${concatExample}`);
console.log(`concatExample2: ${concatExample2}`);

result

[ 'A', 'B', 'C' ]
[ 'A', 'B', 'D', 'E' ]
concatExample: A,B
concatExample2: D,E

slice()

Array를 자름, 원본 Array는 변하지 않음

code

let sliceExample = ['A', 'B', 'C', 'D', 'E'];

console.log(sliceExample.slice(0, 3)); // 0번째 인덱스부터 3개를 반환
console.log(sliceExample);

result

[ 'A', 'B', 'C' ]
[ 'A', 'B', 'C', 'D', 'E' ]

spread operator

code

let spreadExample = ['A', 'B', 'C'];
let spreadExample2 = [
    ...spreadExample,
];
console.log(`spreadExample: ${spreadExample}`);
console.log(`spreadExample2: ${spreadExample2}`);

let spreadExample3 = [
    spreadExample,
];
console.log(`spreadExample3: ${spreadExample3}`);

let arraySample = ['A','B','C','D','E','F','G','H']
let arraySample4 = arraySample;

console.log(arraySample4);
console.log(arraySample4 === arraySample); // true

// console.log([
//     ...arraySample,
// ] === arraySample); // false, 메모리 공간이 다름

result

spreadExample: A,B,C
spreadExample2: A,B,C
spreadExample3: A,B,C
[
  'A', 'B', 'C',
  'D', 'E', 'F',
  'G', 'H'
]
true

join()

Array를 문자열로 변환

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.join()); // Array를 문자열로 변환
console.log(arraySample.join(' ')); // Array를 문자열로 변환, 구분자 추가
console.log(arraySample.join(', ')); // Array를 문자열로 변환, 구분자 추가

result

A,B,C,D,E,F,G,H
A B C D E F G H
A, B, C, D, E, F, G, H

sort() / reverse()

Array를 정렬

code

let arraySample = ['A','B','C','D','E','F','G','H']

console.log(arraySample.sort()); // 오름차순
console.log(arraySample.reverse()); // 내림차순

let numbers = [
    1,
    9,
    7,
    4,
    2,
    6
];
console.log(numbers);

/* a,b를 비교 했을때 */
// 1. a를 b보다 나중에 정렬하려면 (뒤어두려면) 0보다 큰 숫자를 반환
numbers.sort((a, b)=>{
    return a > b ? 1 : -1;
});
console.log(numbers);

numbers.sort((a, b) => a > b ? -1 : 1);
console.log(numbers);

// 2. a를 b보다 먼저 정렬하려면 (앞에 두려면) 0보다 작은 숫자를 반환
// 3. a와 b의 위치를 변경하지 않아도 된다면 0을 반환

result

[
  'A', 'B', 'C',
  'D', 'E', 'F',
  'G', 'H'
]
[
  'H', 'G', 'F',
  'E', 'D', 'C',
  'B', 'A'
]
[ 1, 9, 7, 4, 2, 6 ]
[ 1, 2, 4, 6, 7, 9 ]
[ 9, 7, 6, 4, 2, 1 ]

map()

Array의 모든 요소에 대해 함수를 호출한 결과를 반환, 원본 Array는 변하지 않음

code

const mapExample = ['A', 'B', 'C', 'D', 'E'];

console.log(mapExample.map((x) => x));
console.log(mapExample.map((x) => x + '님'));
console.log(mapExample.map((x) => `Array: ${x}`));

console.log(mapExample.map((x) => {
    if(x === 'B'){
        return `Special ${x}`
    } else {
        return x;
    }
}));
console.log(mapExample);

result

[ 'A', 'B', 'C', 'D', 'E' ]
[ 'A님', 'B님', 'C님', 'D님', 'E님' ]
[ 'Array: A', 'Array: B', 'Array: C', 'Array: D', 'Array: E' ]
[ 'A', 'Special B', 'C', 'D', 'E' ]
[ 'A', 'B', 'C', 'D', 'E' ]

filter()

모든 값 반환

code

numbers = [1, 8, 7, 6, 3];

console.log(numbers.filter((x) => true)); 
console.log(numbers.filter((x) => x % 2 === 0));

result

[ 1, 8, 7, 6, 3 ]
[ 8, 6 ]

find()

가장 첫번째 값 반환

code

numbers = [1, 8, 7, 6, 3];

console.log(numbers.find((x) => x % 2 === 0));

result

8

findIndex()

가장 첫번째 값의 인덱스 반환

code

numbers = [1, 8, 7, 6, 3];

console.log(numbers.findIndex((x) => x % 2 === 0));

result

1

reduce()

누적값 반환

code

numbers = [1, 8, 7, 6, 3];

console.log(numbers.reduce((p, n) => p + n, 0));
    // 설명

    // (p, n) => p + n, 0
    // p : 누적값
    // n : 현재값(numbers[n])
    // 0 : 초기값
    
    // reduce((p, n) => p + n, 0)
    // reduce((누적값, 현재값) => 누적값 + 현재값, 초기값)

    // 1. 0(inital number) + 1(numbers[0]) = 1(p)
    // 2. 1(p) + 8(numbers[1]) = 9(p)
    // 3. 9(p) + 7(numbers[2]) = 16(p)
    // 4. 16(p) + 6(numbers[3]) = 22(p)
    // 5. 22(p) + 3(numbers[4]) = 25(p)

console.log(numbers.reduce((p, n) => p + n, 100));
    // 100 + 1 + 8 + 7 + 6 + 3 = 125

result

25
125
출처: 코드팩토리