본문 바로가기
JavaScript/드림코딩

자바스크립트 기초(ES5+)_유용한 배열(Array)함수 10가지(*중요)

by junvely 2022. 3. 23.

[ 유용한 배열(Array) 함수 ]

 

1. join() > 배열에있는 모든 아이템을 더해서 string으로 리턴함, 각각 구분자''를 통해 ,으로 구분하여 string으로 만들어준다.

// Q1. make a string out of an array
  const fruits = ["apple", "banana", "orange"];
// answer 
  const result = fruits.join();
  const result1 = fruits.join("|"); // 구분자 '|'생성
  console.log(result);
  console.log(result1);

 

- 나 : toString() 사용, 차이가 무엇일까?
 
 
 
2. split() > 전달된 구분자''를 통해 string을 여러가지 문자열로 잘게 나뉘어 전달해 준다. > 나뉜 것들은 배열이 된다.> 원 배열은 변경x
  • 구분자를 꼭 전달해 줘야 한다.(구분x)
  • limit이라는 parameter 전달할수 있다. 첫번째 두개의 배열을 전달받고 싶다면 숫자 2를 입력하면 2개만 전달받는다.
// Q2. make an array out of a string  
  const fruits = "🍎, 🥝, 🍌, 🍒";
// answer 
  const result = fruits.split(",");
  const result1 = fruits.split(",", 2);
  console.log(result); // [🍎, 🥝, 🍌, 🍒]
  console.log(result1); // [🍎, 🥝]

- 나 : 그냥 새 배열을 생성 후 fruits.push 하였다. > 오답 > 배열 안에 ['🍎, 🥝, 🍌, 🍒'] 자체가 들어간다.

 

3. reverse() > 배열안에 들어있는 아이템의 순서를 거꾸로 만들어 준다. > *원 배열 자체의 순서를 변경시킨다.

// Q3. make this array look like this: [5, 4, 3, 2, 1]

//reseult
  const array = [1, 2, 3, 4, 5];
  const result = array.reverse();
  console.log(array);
  console.log(result); // 원 배열의 값도 변경된다.

- 정답ㅇ

 

4. splice(begin, 갯수), slice(start, end)

  • splice(begin, 갯수) > (어디서부터, 몇개를 지울 것인지), 배열 자체에서 삭제시키고, 삭제된 값을 return 한다.
// Q4. make new array without the first two elements > 처음 두 가지 요소를 제외하고 새로운 배열을 만들다

// splice()
  const array = [1, 2, 3, 4, 5];
  const result = array.splice(0, 2);
  console.log(result);
  console.log(array);
  // 새로운 배열을 생성해야 하기 때문에 splice 사용 x

나 : splice() 사용

 

  • slice(start, end) > (시작과, 끝부분 입력), 배열의 특정한 부분을 return한다. > 0-2까지로 지정하면-1,  0과 1만 반환한다.
//result
// slice()
  const result1 = array.slice(2, 5);
  console.log(result1);
  console.log(array);

- splice와 slice의 차이 : splice는 배열 자체를 수정, slice는 배열에서 원하는 부분만 return해서 사용할때 쓴다.

 

5. find() > (this, value, index, obj)전달됨 콜백함수를 만들어서 전달 > 배열에 있는 모든 요소를 호출하여 콜백함수가 true인 첫 번째로 찾아진 요소를 리턴한다. 찾지못하면 undefined 

  • 콜백 함수는 boolean타입을 return 해야 한다.
  • 콜백 함수에 전달되는 인자의 이름은 되도록 한눈에 파악할수 있도록 한다.(특히 한줄의 정리된 코드 일 경우)

- ex1) students > (value)x , (student)o

- ex2) colors > (value)x , (color)o

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

// Q5. find a student with the score 90
{ 
  // result
  // find()
  // const result = students.find(function (student, index) {
  //   return student.score === 90; // true //  콜백 함수는 boolean타입을 리턴한다.
  //   console.log(result);
  // });
  const result = students.find((student, index) => student.score === 90); // 콜백함수는 모든 요소에 대입하여 true를 찾는다.
  console.log(result); // find는 true 중 첫번째를 반환
}

 

6. filter() > 콜백함수를 전달하여 콜백함수가 true 배열을 젼달해 준다. > filter()는 호출되는 배열을 변화시키지 않는다.

// Q6. make an array of enrolled students > 수업에 등록된 true인 학생만 골라 새 배열을 만들기
  // result
  const result = students.filter((student) => student.enrolled); // student.enrolled ===true > true 생략가능
  console.log(result);

 

7. map() > 배열안에 들어있는 요소들에 지정된 콜백함수를 호출하여 함수에서 return된 값으로 가공하여 mapping하여 만들어 주는 것

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]

  // result
  // map() > 배열안에 들어있는 요소들에 지정된 콜백함수를 호출하여 함수에서 return된 값으로 가공하여 mapping하여 만들어 주는 것
  const result = students.map((student) => student.score);
  const result1 = students.map((student) => student.score * 2);
  console.log(result);
  console.log(result1);

 

8. some() , every()

  •   some() > 배열의 요소 중 콜백함수의 return이 true가 되는 것이 있는지 없는지 확인
  •   every() > 배열에 있는 모든 요소들이 콜백함수의 조건을 만족해야지만 true를 반환
// Q8. check if there is a student with the score lower than 50

  //result
  // some() > 배열의 요소 중 콜백함수의 return이 true가 되는 것이 있는지 없는지 확인
  const result = students.some((student) => student.score < 50);
  console.log(result);

  // every() > 배열에 있는 모든 요소들이 콜백함수의 조건을 만족해야지만 true를 반환
  const result1 = !students.every((student) => student.score >= 50); // ! > false > true로반환
  console.log(result1);

 

9. reduce() > 배열에 있는 모든 요소들에 콜백함수 호출하며, 콜백함수에서 return되는 값은 함께 누적된 값을 return한다.

  • 콜백함수에 값을 전달할 때는 '어떤 값이 누적된 값'을 전달해야 한다. 배열의 모든 값을 함께 누적할때 사용한다.
  • reduceRight() > reduce와 동일하나 호출되는 순서가 거꾸로다(D>C>B>A)
// Q9. compute students' average score

  // result
  const result = students.reduce((prev, curr) => {// 이전값과, 현재값을 받아올 수 있다. 
  / curr > 배열의 값이 하나하나 전달이 된다./ return된 값이 pre(이전값)에 전달된다. 누적되며 반복
    console.log("-----");
    console.log(prev); // 이전값
    console.log(curr); // 현재값
    return prev + curr.score;
  }, 0); // 0(시작점) 부터 원하는 값을 누적 A,B,C,D 순차적으로 호출된다.
  console.log(result);

  // 간략히
  const result1 = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(result1 / students.length); // 평균 구하기

 

10. 함수형 프로그래밍(새로운 배열을 return하는 api들을 섞어서 사용 가능하다.)

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88' > 문자로 출력

  // result
  // 함수형 프로그래밍
  const result = students
    .map((student) => student.score) // 학생들의 점수를 새로 mapping함 > 새로운 배열로 return함 > 배열 자체를 return하기 때문에 다시 배열api사용가능하고, 섞어서 호출도 가능하다.
    .filter(student.score >= 50) // 50점이상 학생들 점수만
    .join();
  console.log(result);

 

11. sort() > 콜백함수에는 이전값(a)과 현재값(b)을 전달하고, a-b했을 때, b(뒤의값)가 더 크다면 오름차순, 반대면 내림차순

// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'

  //result
  // sort() > 콜백함수에는 이전값(a)과 현재값(b)을 전달하고, a-b했을 때, b가 더 크다면 오름차순, 반대면 내림차순
  	const result = students
    .map((student) => student.score) // student의 score로 mapping
    .sort((a, b) => a - b) // 오름차순
    // .sort((a, b) => b - a) // 내림차순
    .join();
  	console.log(result);

 

 

 

*본 포스팅은 드림코딩 유튜브강의를 정리한 내용입니다.