자바스크립트에서 유용하게 쓰이는 10가지 배열함수들

지선·2021년 7월 23일
0

10가지 예제를 통해, 자주쓰이는 배열 함수를 알아보자!


예제문제


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

1. array.join('구분자') : 배열 -> 문자열로 변환시켜주는 함수


//1. make a string out of an array

    const fruits = ['apple', 'banana', 'orange'];
    const result = fruits.join(',');//string으로 변환
    console.log(result);

2. array.split('구분자') : 문자열 -> 배열로 변환시켜주는 함수


//2. maek an array out of a string

    const fruits='사과, 키위, 배, 딸기';
    const result = fruits.split();
    console.log(result);

3. array.reverse() : 배열 순서를 바꾸는 함수


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

    const array = [1,2,3,4,5]
    const result = array.reverse();
    console.log(result);
    console.log(array)// 배열자체 순서도 바뀜

4-1. array.slice(start,end+1) : 배열 인덱스 start에서 end까지 발췌하는 함수


 //4. make new array without the first two elements
	
    const array =[1,2,3,4,5];
    const result = array.slice(2,5);//end값은 배제된다
    console.log(result);[3,4,5]
    console.log(array);//[1,2,3,4,5]원본배열 유지

4-2. array.splice(start,deletecount) : start에서 deletcount개수만큼 삭제하고, 삭제된 배열을 보여주는 함수


//4. make new array without the first two elements

    const array = [1,2,3,4,5];
    const result = array.splice(2,3);//삭제된 데이터를 보여줌
    console.log(result);//[3,4,5]
    console.log(array); //[1,2] 남아있는 배열만 나옴
    
    //이렇게 하면 array값이 손상되니깐 ㄴㄴ
    

5. array.find( (item) => item.key 조건 ) : 조건에 해당되면 true를 반환해줌.


// Q5. find a student with the score 90

	const result = students.find(
    	//find는 여러개의 해당값이 있어도 처음 한개만 찾아줌
        (student) => student.score === 90
    )
   console.log(result)

6. array.filter( (item) => item.key 조건 ) : 조건에 해당되는 item을 모두 반환해줌.


  // Q6. make an array of enrolled students
  
      const result = students.filter((student) => student.enrolled)
      console.log(result);

7. array.map((item) => item.key 수정조건) : 전체 배열값을 불러오기, 일괄적으로 더하거나 빼기등 수정가능.


// Q7. make an array containing only the students' scores 
	result should be: [45, 80, 90, 66, 88]
    
      const result = students.map((student) => student.score)
      //콜백함수 안에 item,value등을 넣을수도 있지만, 
      이해하기 가장 쉬운것을 쓰는게 중요!
      console.log(result);

8-1. array.some((item) => item.key 조건) : 콜백함수가 만족되면 true 출력


// Q8. check if there is a student with the score lower than 50
  
      const result = students.some((student) => student.score < 50);//콜백함수가 만족되면 true출력
      console.log(result);

8-2. array.every((item) => item.key 조건) : 배열의 모든값이 콜백함수에 만족되면 true출력


    const result2 = !students.every((student) => student.score >= 50);
    //배열의 모든값이 콜백함수에 만족되면 true출력
    console.log(result2)

9. array.reduce((prev,curr) => ,초깃값)


가장 헷갈리는 함수이기도 한... reduce()
쉽게 생각해서, 배열 하나하나를 돌면서 값을 누적할때 쓰는 함수다.

말로만 하면 이해가 안되서, 콘솔창에 찍으면서 이해하자.

보는것 처럼 초깃값을 0으로 준다.

첫번째 curr.score와 두번째 prev값이 같은것을 알 수 있다. 그러므로 curr과 prev.score를 반복해서 더해주면, 총합계를 구할 수 있음!

// Q9. compute students' average score
  
      const result = students.reduce((prev,curr) => prev + curr.score, 0) 
      //배열하나하나를 돌면서 값을 누적할때 쓰임
      
      console.log(result / students.length)

10. array. sort() : 오름차순, 내림차순


Q10 sorted in ascending order
  // result should be: '45, 66, 80, 88, 90'
  {
      const result = students
        .map(student => student.score)
        .sort((a,b) => b-a)//내림차순 a-b
        .join();

      console.log(result);
  }

+. 섞어쓰기


// Q10. make a string containing all the scores
  // result should be: '45, 80, 90, 66, 88'
  {
      const result = students
        .map((student) => student.score)
        .filter((score) => score >= 50)
        .join();
      console.log(result);
  }
  • 로직도 더 쉽게 잘 볼 수 있음! 깔~끔!
profile
프론트엔드개발자가 될거야!

0개의 댓글