#TIL30, Javascript 자주 사용하는 배열 method

April·2021년 5월 28일
0

✨Javascript

목록 보기
10/45
post-thumbnail

개인 공부를 위해 작성했습니다

2차 프로젝트의 반이 지났다.. 그런데 왜 난 기본적인 것으로 헤매고 있는 것인가..🥲
westagram, 1차 프로젝트, 코드카타 풀며 filter나 map, foreach, spread operator를 몇 번씩 사용해보며 익혔다고 생각했는데.. 기초가 흔들리는 내 자신을 마주하니 현타가 급..😱😱😱😱
그래서 정리해본다! 자주 사용하는 배열 메소드!!


1. join()

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
원본 배열은 바꾸지 않음.

arr.join(separator)
*separator(구분자): ,, /, "등의 구분자. 있어도 되고, 없어도 된다.

이 때 🚩주의할 점은, 구분자를 string타입으로 전달해야한다는 점!! (그렇지 않을 경우 에러 발생)
, and 처럼 string으로 구분자를 만들어 줄 수도 있다

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(); // separator(구분자) 생략의 경우
console.log(result); // apple, banana, orange

const result = fruits.join('|'); // 구분자 입력 후 
console.log(result); // apple|banana|orange

2. split()

stringarray로 만들어 주는 메서드. 원본 string은 변화시키지 않음.

str.split(separator)
*separator(구분자): ,, /, "등의 구분자. 있어도 되고, 없어도 된다.

split에 구분자를 전달하지 않으면 문자열 전체가 배열의 한 요소로 들어가기 때문에 꼭 구분자를 전달해야 한다.

const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(','); // separator(구분자=나눌 단위), limit(단위 지정)
                                 // 문자를 구분하는 , 기준으로 구분
console.log(result);  // ['🍎', '🥝', '🍌', '🍒']

const result = fruits.split(',', 2); // separator(구분자=나눌 단위), limit(단위 지정)
console.log(result);  // ['🍎', '🥝']

3. reverse()

순서가 뒤집힌 배열을 반환해주는 배열 메서드.
원본 배열을 변환한다🌟🌟🌟🌟🌟

arr.reverse()

const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result); // [5, 4, 3, 2, 1]
console.log(array); // [5, 4, 3, 2, 1]

4. splice(); | slice();

splice()

인덱스로 시작부분과 끝나는 부분을 지정해주면, 지정된 부분을 삭제. 그리고 삭제된 요소들이 return 된다.
원본 배열에서 데이터를 삭제하기 때문에 원본 배열을 변환한다. 배열 자체를 수정🌟🌟🌟🌟🌟

arr.splice(시작인덱스, 삭제할 요소의 수)

const array = [1, 2, 3, 4, 5];
const result = array.splice(0,2); // start number(어디서 부터 삭제할 것 인가), deleteCount(얼만큼 지울 것인가)
console.log(result); // 삭제된 값이 출력됨 [1, 2]
console.log(array); // [3, 4, 5]

slice()

배열의 특정 부분을 반환하는 배열 메소드.
원하는 부분만 가지고 와서 새로운 배열을 만들어야 한다면 slice()메소드를 사용.
원본 배열을 변경하지는 않는다.

arr.slice(시작인덱스, 끝인덱스)
*끝인덱스: 반환을 원하는 마지막 요소의 인덱스로, 끝인덱스는 exclusive 하기 때문에 사실상 '가져올 마지막 요소의 인덱스 + 1'이 된다.

// 새로운 배열을 만드는게 Quiz 였으므로, 다시 풀기
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5); //start number, end number
onsole.log(result); // [3, 4, 5]
console.log(array); // [1, 2, 3, 4, 5]

5. find()

콜백함수의 조건을 충족하는 첫번째로 찾아진 요소를 리턴하는 메소드.
배열의 모든 요소를 순차적으로 돌면서 콜백함수를 호출하다가, 콜백함수에 true를 리턴하는 요소를 찾으면 곧바로 리턴.
조건을 충족하는 요소를 찾지 못했을 경우, undefined를 리턴.

arr.find(콜백함수(this, value, index, obj))
*콜백함수: return값으로 boolean타입의 값을 리턴한다.

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

const result = students.find(predicate(students){ // predicate(this, value, index, obj), thisArg
  return students.score === 90;                   // predicate라는 콜백 함수에 this, value, index, obj라는 인자를 받음
); 																					      // 값을 boolean으로 받는다
console.log(result);

// ↓ arrow function으로 변경한 문법
const result = students.find((students) => students.score === 90; 
console.log(result);

6. filter()

콜백함수의 조건을 충족하는 (반환값이 true인)요소들만 모아서 새로운 배열로 리턴해주는 메소드.
원본 배열을 변경하지는 않는다.

arr.filter(콜백함수(value, index, array))
*콜백함수: return값으로 boolean타입의 값을 리턴한다.

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

const result = students.filter((student) => student.enrolled);
console.log(result);

7. reduce();

배열을 돌면서 모든 요소들에 콜백함수를 실행해 누적된 값을 리턴한다.
현재값이 다음 loop에서는 이전값이 되어 전달된다.
즉, 배열을 돌면서 특정 시작점 값에 콜백함수가 실행된 값을 누적해나간다.
원본 배열은 변경하지 않는다.

arr.reduce(콜백함수(이전값, 현재값, 현재인덱스, 배열), 초기값)
*콜백함수: return값을 정해주지 않으면 누적값이 저장되지 않아 undefined를 반환한다. return값 정해주기

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

const result = students.reduce((prev, curr) => prev + curr.score, 0); // 배열에 있는 모든 값을 누적하는 API
console.log(result / students.length); // 73.8

8. sort()

sort() 메소드를 사용하면 배열을 오름차순 혹은 내림차순으로 재정렬 할 수 있다

오름차순 (Ascending order)
arr.sort((a, b) => a - b);
내림차순(Descending order)
arr.sort((a, b) => b - a);

9. 전개 구문(spread operator)

문법 이름 그대로 객체 혹은 배열들을 펼칠 수 있게 해 준다.
펼쳐진 객체나 배열을 담을 바구니가 필요하다.
객체는 객체로, 배열은 객체나 배열로 담아낼 수 있다.

// 펼칠 대상이 객체인 경우
{...obj}


// 펼칠 대상이 배열인 경우
[...arr]
// 혹은
{...arr}

concat()

기존 배열에 새로운 요소를 추가하여 새로운 배열을 만드는 경우 사용한다

var arr = [1, 2, 3];
console.log(arr.concat([4, 5, 6])); // [ 1, 2, 3, 4, 5, 6 ]

ES6에서는 concat 대신 Spread 문법을 사용하여서 동일한 결과를 얻을 수 있다

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

push()

.push() 메소드를 사용하면 특정 배열에 다른 배열의 각 요소를 추가할 수 있다

const arr1 = [1,2,3]
const arr2 = [4,5,6]
Array.prototype.apply(arr1, arr2)
console.log(arr1)//[1,2,3,4,5,6]

전개구문을 사용하는 경우 보다 간편하게 동일한 결과를 얻을 수 있다.

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

정리!

:: 원본을 변경하는 메소드

  1. splice(): 지정된 부분을 삭제
  2. push(): 배열에 요소를 추가

:: 원본을 변경하지 않는 메소드

  1. join(): arraystring
  2. split(): stringarray
  3. slice(): 배열의 특정 부분을 반환
  4. find(): 조건을 충족하는, 첫번째로 찾아진 요소를 리턴
  5. filter(): 조건을 충족하는 (반환값이 true인)요소들만 모아서 리턴
  6. reduce(): 배열을 돌면서 모든 요소들에 콜백함수를 실행해 누적된 값을 리턴
  7. concat():기존 배열에 새로운 요소를 추가하여 새로운 배열을 만드는 경우 (ES6에서는 전개구문으로 사용)

드림코딩

profile
🚀 내가 보려고 쓰는 기술블로그

0개의 댓글