ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 배열 객체 완벽 가이드
    웹개발/JavaScript 2024. 7. 27. 17:53
    728x90

    자바스크립트의 배열 객체

    안녕하세요, 친구들! 오늘은 자바스크립트에서 자주 사용하는 **배열 객체(Array)**에 대해 배워볼 거예요. 배열 객체는 데이터를 쉽게 다루고 조작할 수 있게 해주는 다양한 메서드를 제공해요. 함께 알아볼까요? 🚀


    배열 객체 생성

    배열 객체를 생성하는 방법은 아주 간단해요. 예를 들어볼까요?

    let arr = [10,20,30];

    이렇게 하면 숫자 10, 20, 30이 들어있는 배열이 생성돼요.

     

    .push()

    push 메서드는 배열의 끝에 새로운 요소를 추가해요.

    let arr = [10, 20, 30];
    arr.push(40);
    console.log(arr); // [10, 20, 30, 40]

     

    .shift()

    shift 메서드는 배열의 첫 번째 요소를 제거하고, 제거된 요소를 반환해요.

    let arr = [10,20,30];
    let removeElement = arr.shift();
    console.log(removeElement); // 10;
    console.log(arr); // [20,30]

     

    .unshift(value)

    unshift 메서드는 배열의 앞에 새로운 요소를 추가해요.

    let arr = [10, 20, 30];
    arr.unshift(5);
    console.log(arr); // [5, 10, 20, 30]

     

    .join([separator])

    join 메서드는 배열의 모든 요소를 문자열로 합쳐요. 선택적으로 구분자를 넣을 수 있어요.

    let numbers = [1, 2, 3, 4, 5];
    console.log(numbers.join("-")); // "1-2-3-4-5"
    console.log(numbers.join("")); // "12345"
    console.log(numbers.join()); // "1,2,3,4,5"

     

    .sort()

    sort 메서드는 배열을 정렬해요. 기본적으로 문자열로 정렬되지만, 숫자나 객체를 정렬할 때는 비교 함수를 사용해요.

    1) 문자열 오름차순 정렬 => 기본 문법 이용

    let arr = ["a", "d", "z", "p", "j", "c", "k", "s"];
    arr.sort();
    console.log(arr);	//['a', 'c', 'd','j', 'k', 'p','s', 'z']

    2) 문자열 내림차순 정렬 => 비교 연산자(<, >) 이용

    var strArray = ["BA", "BB", "AA", "AB", "CB", "CA"];
    
    strArray.sort(function compare(a, b) {
      if (a > b) return -1;
      if (a < b) return 1;
      return 0;
    });
    
    console.log(strArray); // ["CB","CA","BB","BA","AB","AA"]

    3) 한자리 수 정렬

    let arr1 = [1, 4, 6, 8, 5, 3, 7];
    arr1.sort();
    console.log(arr1); 	// [1, 3, 4, 5, 6, 7, 8]

    4) compareFunction생략한 채로 정렬 => 오류 발생

    let arr2 = [74, 1, 8, 54, 23];
    arr2.sort();
    console.log(arr2); //[ 1, 23, 54, 74, 8 ] => 오류 발생

    sort()함수는 정렬할 때 배열의 요소들을 문자열로 취급 => 숫자 정렬시 값을 비교해줄 수 있는 함수 넣어줘야함!

    5) 숫자 정렬(오름차순) => a-b

    let arr3 = [13, 46, 52, 36, 75, 3];
    arr3.sort(function (a, b) {
      return a - b;
    });
    // arr3.sort((a, b) => a - b);  //화살표 함수 이용
    console.log(arr3); //[ 3, 13, 36, 46, 52, 75 ]

    a, b 에 두 요소 전달해서 a-b로 크기를 비교한 후에

    a>b이면 양수, a-b이면 음수를 리턴하여, 주어진 배열을 오름차순 정렬함.

    6) 숫자 정렬(내림차순) => b-a

    let arr3 = [13, 46, 52, 36, 75, 3];
    
    arr3.sort(function (a, b) {
      return b - a;
    });
    console.log(arr3); //[ 75, 52, 46, 36, 13, 3 ]

    오름차순과 반대로 b-a를 해주면 내림차순으로 정렬됨을 볼 수 있다.

     

    .reverse()

    reverse 메서드는 배열의 순서를 역순으로 뒤집어요.

    let numbers = [4, 2, 5, 1, 3];
    numbers.reverse();
    console.log(numbers); // [3, 1, 5, 2, 4]

    연습문제

    const students = [
      { name: "Alice", age: 21, gender: "female", height: 170 },
      { name: "Bob", age: 19, gender: "male", height: 165 },
      { name: "Charlie", age: 20, gender: "male", height: 175 },
      { name: "David", age: 22, gender: "male", height: 180 },
      { name: "Eve", age: 17, gender: "female", height: 160 },
      { name: "Frank", age: 18, gender: "male", height: 175 },
      { name: "Grace", age: 21, gender: "female", height: 165 },
      { name: "Henry", age: 19, gender: "male", height: 170 },
      { name: "Ivy", age: 10, gender: "female", height: 155 },
      { name: "Jack", age: 22, gender: "male", height: 185 },
    ];
    
    // 1. 키가 185인 학생 찾기
    {
      const student = students.find((student) => student.height === 185);
      console.log(student); // { name: 'Jack', age: 22, gender: 'male', height: 185 }
    }
    
    // 2. 나이가 20살 이상인 학생들 찾기
    {
      const studentList = students.filter((student) => student.age >= 20);
      console.log(studentList);
    }
    
    // 3. 키가 165 이하인 학생들이 있는지 찾아서 true, false로 반환하기
    {
      const isStudent = students.some((student) => student.height <= 165);
      console.log(isStudent); // true
    }
    
    // 4. 학생들이 모두 10살 이상인지 확인해서 true, false 반환하기
    {
      const isStudentover10 = students.every((student) => student.age >= 10);
      console.log(isStudentover10); // true
    }
    
    // 5. 학생들의 평균 연령 구하기
    {
      const totalAge = students.reduce((acc, student) => acc + student.age, 0);
      const averageAge = totalAge / students.length;
      console.log(averageAge); // 18.2
    }
    
    // 6. 남학생들의 평균 연령 구하기
    {
      const maleStudents = students.filter((student) => student.gender === "male");
      const totalMaleAge = maleStudents.reduce((acc, student) => acc + student.age, 0);
      const maleAverageAge = totalMaleAge / maleStudents.length;
      console.log(maleAverageAge); // 19.285714285714285
    }
    
    // 7. 여학생들만 따로 추출해서 새로운 배열 만들기
    {
      const femaleStudents = students.filter((student) => student.gender === "female");
      console.log(femaleStudents);
    }
    
    // 8. 여학생들 중 나이가 가장 어린 학생 찾기
    {
      const youngestFemaleStudent = students
        .filter((student) => student.gender === "female")
        .sort((a, b) => a.age - b.age)[0];
    
      console.log(youngestFemaleStudent); // { name: 'Ivy', age: 10, gender: 'female', height: 155 }
    }
    728x90
Designed by Tistory.