개발기록장

[Javascript] array method (배열 메소드) 정리 본문

TIL/JavaScript

[Javascript] array method (배열 메소드) 정리

yangahh 2020. 12. 20. 02:45

 

자바스크립트의 유용한 array method에 대해 정리해보자.

 

1. push / pop

  • push : 배열의 맨 뒤에 원소 추가 (원 배열 변경)
  • pop : 배열의 맨 뒤 원소 제거 (원 배열 변경)
let fruits = ['apple', 'banana'];

// push
fruits.push('c', 'd');
console.log(fruits);	// ["apple", "banana", "c", "d"]

// pop
let item = fruits.pop(); // 삭제되는 원소를 반환하기 때문에 변수에 저장 가능
console.log(item);	// d
fruits.pop();
console.log(fruits);	// ["apple", "banana"]

 

 

 

2. unshift / shift

  • unshift : 배열의 맨 앞에 원소 추가 (원 배열 변경)
  • shift : 배열의 맨 뒤에 원소 추가 (원 배열 변경)

 

// unshift
fruits.unshift('a', 'b');
console.log(fruits);	// ["a", "b", "apple", "banana"]

// shift
fruits.shift();
fruits.shift();
console.log(fruits);	// ["apple", "banana"]

** unshift와 shift는 한 번 수행할 때 마다 원소들의 위치를 땡겨오거나 미뤄야해서 push와 pop에 비해 매우 느리다.

 

 

 

3. splice

splice는 지정된 위치의 원소들을 제거할 수 있다. 또한 제거함과 동시에 원소들을 추가할 수도 있다. (원 배열 변경)

 

syntax :

array.splice(제거 시작 인덱스 번호, 제거하고 싶은 원소 개수(옵션, 지정하지 않을 시 시작 인덱스 번호 이후 모든 원소 제거), 추가할 원소들(옵션))

fruits = ['apple', 'banana', 'a', 'b', 'c', 'd'];

fruits.splice(1, 1);	// 인덱스 1번부터 1개의 원소 삭제
console.log(fruits);	// ["apple", "a", "b", "c", "d"]

fruits.splice(1, 2, 'x', 'y');	// 인덱스 1번부터 2개의 원소 삭제하고 그 위치에 'x', 'y' 삽입
console.log(fruits);	// ["apple", "x", "y", "c", "d"]

fruits.splice(1);
console.log(fruits);	// ["apple"]

 

 

 

4. concat

서로 다른 두 배열 합치기

fruits1 = ['apple', 'banana'];
fruits2 = ['mellon', 'strawberry'];

let newFruits = fruits1.concat(fruits2);
console.log(newFruits);  // ['apple', 'banana', 'mellon', 'strawberry']

 

 

 

5. indexOf / lastIndexOf

둘 다 해당 원소가 몇 번째 인덱스에 있는지 확인할 때 쓰이지만 아래와 같은 차이점이 있다

  • indexOf : 같은 원소가 여러 개 있는 경우에는 맨 앞에 있는 것에 대한 인덱스 정보만 반환
  • lastIndexOf : 같은 원소가 여러개 있는 경우에는 맨 마지막에 있는 것에 대한 인덱스 정보만 반환
let arr = ['a', 'b', 'c', 'a', 'e']

console.log(arr.indexOf('a'));  // 0
console.log(arr.lastIndexOf('a'));  // 3

console.log(arr.indexOf('x'));  // -1
console.log(arr.lastIndexOf('x'));  // -1

 

 

 

 

 

6. includes

배열에 해당 item이 있는지 없는지 확인. true/false로 반환

let arr = ['a', 'b', 'c', 'a', 'e']

console.log(arr.includes('a'));	 // true
console.log(arr.includes('x'));	 // false

 

 

7. join

배열에 있는 요소들을 구분자를 추가해서 하나의 string으로 합치기

fruits = ['apple', 'banana', 'mellon', 'strawberry'];

let result;
result = fruits.join(); 
console.log(result); 	// apple,banana,mellon,strawberry

result = fruits.join(' | ');
console.log(result); 	// apple | banana | mellon | strawberry

 

 

 

8. split

string을 특정 구분자를 기준으로 나눠서 배열로 만들기

let stringFruits = "apple, banana, strawberry";
let arrayFruits = stringFruits.split(", ");

console.log(arrayFruits); 	// ["apple", "banana", "strawberry"]

 

 

 

9. slice

기존 배열을 쪼개서 새로운 배열 생성 (원 배열 보존)

syntax :

array.slice(시작 인덱스, 끝 인덱스+1);

fruits = ["apple", "banana", "mellon", "strawberry"];

const sliceFruits = fruits.slice(1, 3);	// 인덱스 1부터 2까지
console.log(sliceFruits);	// ["banana", "mellon"]

 

 

 

10. filter / map

  • filter : 배열에서 원하는 조건의 요소만 걸러냄
  • map : 배열 안에 들어있는 요소 하나하나를 함수를 거쳐서 새로운 값으로 변환
class Student {
    constructor(name, age, enrolled, score) {
        this.name = name;
        this.age = age;
        this.enrolled = enrolled;
        this.score = score;
    }
}

const students = [
    new Student('A', 29, true, 45),
    new Student('B', 28, false, 80),
    new Student('C', 30, true, 90),
    new Student('D', 40, false, 66),
    new Student('E', 18, true, 88), 
]


// filter
// ex) enrolled이 true인 학생들만 걸러내기
result = students.filter(function(student){  // student는 students 배열에 있는 item을 말함
    return student.enrolled;
});

//// allow function 이용하면
result = students.filter((student) => student.enrolled);

console.log(result);  // [Student, Student, Student]
/* 결과
0: Student {name: "A", age: 29, enrolled: true, score: 45}
1: Student {name: "C", age: 30, enrolled: true, score: 90}
2: Student {name: "E", age: 18, enrolled: true, score: 88}
*/



// map
// ex) students의 요소들에서 score 점수만 배열로 만들기

result = students.map((student) => student.score);
console.log(result);  // [45, 80, 90, 66, 88]