본문 바로가기

js

[javascript] 배열 함수/Array APIs 총정리

1. join()

 

배열을 string으로 변환

// 배열을 string으로 변환
const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join();
// 결과값 : apple,banana,orange

// 구분자 전달
const result = fruits.join(|);
// 결과값 : apple|banana|orange

 

 

2. split()

 

.split('구분자', Limit);

string을 배열로 변환

구분자를 지정하지 않으면 하나의 문자열로 배열이 생성됨

// string을 배열로 변환
const fruits = 'apple', 'banana', 'orange';
const result = fruits.split(',');
// 결과값 : ["apple","banana","orange"]

 

 

3. reverse()

 

배열 자체의 순서를 거꾸로 변경

const array = [1, 2, 3, 4, 5];
const result = array.reverse();
// 결과값 : [5, 4, 3, 2, 1]
// 배열 자체의 순서가 바뀜

 

 

4. splice(), slice()

 

splice는 배열의 특정 부분을 삭제하는 것

.splice(start, end)

fruits.push('strawberry', 'peach');
console.log(fruits);
// (4) ["apple", "banana", "strawberry", "peach"]


// 삭제할 개수를 정하지 않으면 정한 위치부터 뒤에 모든 아이템을 삭제함
frutis.splice(1);
// (1) ["apple"]


// 인덱스 1부터 1개를 삭제( =index 1만 삭제됨)
frutis.splice(1, 1);
// (3) ["apple", "strawberry", "peach"]


// 인덱스 1부터 1개를 삭제하고 그 자리에 'lemon', 'orange'를 추가함
frutis.splice(1, 1, 'lemon', 'orange');
// (5) ["apple", "lemon", "orange", "strawberry", "peach"]

 

slice는 배열의 특정 부분을 리턴하는 것

.slice(start, end)

// 1, 2를 지우고 새로운 배열 생성
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5)
// 결과값 : [3, 4, 5]
// end값을 4로 하면 인덱스 4를 가진 5가 제외되기 때문에 end를 5로 설정

 

 

5. find()

 

찾자마자 찾은 값을 리턴, 찾지 못하면 undefined을 리턴

콜백함수로 리턴 받아야 함

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),
];

// score가 90인 student를 찾아라
const result = students.find(function(student){
	return student.score === 90;
});

//arrow function
const result = students.find((student) => student.score === 90);

 

 

6. filter()

 

콜백함수로 true인 값만 모아서 배열로 만들어주는 함수

// enrolled가 true인 student를 찾아라
const result = students.filter(function(student){
	return student.enrolled;
});

//arrow function
const result = students.filter((student) => student.enrolled);

 

 

7. fill()

 

빈 배열을 원하는 값으로 채워줌

Array(7)
// 빈 배열 생성

Array(7).fill()
// [undefined, undefined, undefined, undefined, undefined, undefined, undefined]

Array(7),fill(7)
// [7, 7, 7, 7, 7, 7, 7]

 

 

8. map()

 

배열 안에 들어 있는 값을 새로운 배열로 만들 수 있음(기존 배열은 바뀌지 않음)

const array = [1, 2, 3, 4];

array.map((element, i) => {
	return element * 2;
})
// 결과값 [2, 4, 6, 8]

Array(7).fill(0).map((el, idx) => {
	return idx + 1;
})
// 결과값 [1, 2, 3, 4, 5, 6, 7]

 

 

9. forEach

.forEach((element, index) => {})

 

 

10. some(), every()

 

some()

하나라도 해당하는 게 있으면 true를 반환

every()

모두가 해당하면 true를 반환

// score가 50 이하인 student가 한명이라도 있는 지

const result = students.some((student) => student.score < 50);
// 결과값 : true

 

 

11. reduce()

 

콜백, 이니셜함수

배열에 있는 모든 요소들의 값을 하나하나 누적시킬 때 사용

 

[배열요소].reduce((누적값, 현재값) => (누적값+ 현재값, 초기값)

초기값을 넣지 않으면 첫번째 값이 초기값이 됨

[1, 2, 3, 4].reduce((a, c) => (a + c), 0)
// a: 0, c: 1
// a: 1, c: 2
// a: 3, c: 3
// a: 6, c: 4
// 결과값 10

 

배열을 객체로

['철수', '영희', '지원', '지혜'].reduce((a, c, i) => {a[i] = c; return a}, {})
// a: {}, c: '철수', i: 0
// a: {0: '철수'}, c: '영희', i: 1
// a: {0: '철수', 1: '영희'}, c: '지원', i: 2
// a: {0: '철수', 1: '영희', 2: '지원'}, c: '지혜', i: 3
// a: {0: '철수', 1: '영희', 2: '지원' 3: '지혜'}

 

reduceRight()

거꾸로 호출함

// student의 score값 평균

const result = students.reduce((prev, curr) => {
    console.log(prev);
    console.log(curr);
    // curr 배열 하나씩 curr에 전달됨
    // prev 이전에 리턴했던 값(curr)이 prev로 전달됨
    
    return prev + curr.score; // 배열 안에 score값을 순차적으로 더함
    console.log(result / students.length);
}, 0); // 이니셜 value --> 0부터 시작하면서 curr


const result = students.reduce((prev, curr) => prev + curr.score,
console.log(result / students.length);

 

 

12. push(), pop(), unshift(), shift()

 

배열의 추가, 삭제, 결합

unshift, shift 보다 push, pop가 빠름(push, pop를 사용하는 게 좋음)

// push 배열 끝에 아이템을 추가
fruits.push('strawberry', 'peach');
console.log(fruits);
// (4) ["apple", "banana", "strawberry", "peach"]


//pop 배열 끝부터 아이템을 삭제
fruits.pop();
console.log(fruits);
// (3) ["apple", "banana", "strawberry"]
fruits.pop();
console.log(fruits);
// (2) ["apple", "banana"]


//unshift 배열 앞에 아이템을 추가
fruits.unshift('strawberry', 'peach');
console.log(fruits);
// (4) ["strawberry", "peach", "apple", "banana"]


// shift 배열 앞부터 아이템을 삭제
fruits.shift();
console.log(fruits);
// (3) ["peach", "apple", "banana"]

 

 

13. concat

 

배열 합치기

const fruits2 = ['lime', 'coconut'];
const newfruits = fruits.concat(fruits2);
// fruits와 fruits2가 합쳐짐

 

 

14. includes(), indexOf(), lastindexOf()

 

includes

내가 찾는 값이 배열에 존재하는지 true, false로 반환

 

indexOf

내가 찾는 값이 몇번째에 있는지 반환

배열 안에 찾는 값이 존재하지 않으면 -1을 반환

 

lastindexOf

배열 안에 내가 찾는 값과 같은 값이 또 존재할 때

indexOf를 사용하게 되면 내가 찾는 값의 첫번째 인덱스를 반환

lastindexOf를 사용하게 되면 내가 찾는 값의 마지막 인덱스를 반환

console.log(fruits.indexOf('apple'));
// 0

console.log(fruits.includes('apple'));
// true

 

 

15. 여러 가지 API 같이 사용

 

student의 score값을 string으로 변환

const result = students.map((student) => student.score).join();

const result = students
	.map((student) => student.score)
	.join();

 

낮은 score가 string으로 먼저 나오게

const result = students.map(student => student.score)
	.sort((a, b)=> a - b)
    // b가 더 크다면 마이너스 value가 됨(높은 점수부터 정렬됨)
    .join();

 

 

으앙 어렵당 복습하자