loading

새소식

JS Library/React

[React] 리액트 Array 배열 개념 및 활용 + 연습문제

  • -
728x90
반응형

배열 (Array)

  1) 배열 초기화

const arr1 = new Array(); 	// new 사용
const arr2 = [1, 2]; 		// 대괄호 사용

 2) 인덱스를 이용한 접근

const animals = ['🐶', '🐱', '🐷'];
console.log(animals);
console.log(animals.length);
console.log(animals[0], animals[2]);
console.log(animals[3]); // undefined
console.log(animals[animals.length - 1]); // last

 

 3) 반복문을 이용한 요소 제어 

 

const animals = ['🐶', '🐱', '🐷'];

// 고전적인(전통적인) 방법 //
for (let i = 0 ; i < animals.length; i++ ) {
 console.log(i, animals[i]);
}


// inex(key)를 알아낸 후 value 확인 ( for ... in ) //
for(const key in animals) {
console.log(key);
}

// 모든 value를 순서대로 하나씩 꺼내어 확인 (for … of) //
for(const value of animals) {
console.log(value);
}

// forEach 이용(모든 요소의 수만큼 반복하면서 접근 가능) // 
animals.forEach(function(animal, index, array) {
  console.log(`${animal} | ${index} | ${array}`);
});

// forEach 이용 + 화살표 함수 // 
animals.forEach((animal, index, array) => {
  console.log(`${animal} | ${index} | ${array}`);
});

※ forEach() 의 파라미터 => forEach( a, b, c) 

a = value (string) 

b = index (number)

c = array (string[ ])

 

 4) 배열의 요소 추가

const animals = ['🐶', '🐱', '🐷'];

// 배열의 마지막에 요소 추가 (push) //
animals.push('🐵');
console.log(animals);

// 지정된 인덱스에 요소 추가 (이미 요소가 있다면 값 수정) //
animals[5] = '🐰';
console.log(animals);

5) 배열의 요소 제거

// 배열의 마지막 요소 삭제 (pop) //
const animals = ['🐶', '🐱', '🐷', '🐵', '🦝', '🐰'];
animals.pop();
console.log(animals);

// 배열의 처음 요소 제거 (shift) //
const animals = ['🐶', '🐱', '🐷', '🐵', '🦝', '🐰'];
animals.shift();
console.log(animals);

// 배열의 처음에 요소 추가 (unshift) //
const animals = ['🐶', '🐱', '🐷', '🐵', '🦝', '🐰'];
animals.unshift('🐔');
console.log(animals);

 

6) 배열 API

① 찾기

    - includes : 요소 포함 여부    //  includes(searchElement: T, fromIndex?: number): boolean;

const array = ['🍕', '🍔', '🍟', '🌭', '🍖'];
console.log(array.includes('🍔')); // true
console.log(array.includes('🍙')); // false

 

 

    - indexOf : 요소의 위치   //  indexOf(searchElement: T, fromIndex?: number): number;

const array = ['🍕', '🍔', '🍟', '🌭', '🍖'];
console.log(array.indexOf('🍔')); // 1
console.log(array.indexOf('🍙')); // -1
console.log(array.indexOf('🍖')); // 4

 

  - find : 해당 요소 1개   //  find(predicate: (value: T, index: number, obj: T[])

const array = [10, 23, 29, 33, 37, 40];
let result = array.find((value, index, arr) => {
console.log(value, index, arr);
return value % 3 == 0;
});
console.log(result);

 

  - filter : 해당하는 요소를 찾은 후 배열 생성   // filter(predicate: (value: T, index: number, array: T[])

const array = [10, 23, 29, 33, 37, 40];
let result = array.filter((value, index, arr) => {
console.log(value, index, arr);
return value % 2 == 0;
});
console.log(result);

  - some : 해당 요소가 1개 이상이면 true  //  some(predicate: (value: T, index: number, array: T[])

const array = [10, 23, 29, 33, 37, 40];
let result = array.some((value, index, array) => {
console.log(value, index, array);
return value > 20;
});
console.log(result);

 

  - every : 모든 요소가 해당하면 true    //  every(predicate: (value: T, index: number, array: T[])

const array = [10, 23, 29, 33, 37, 40];
let result = array.every((value, index, array) => {
console.log(value, index, array);
return value > 20;
});
console.log(result);

 

② 기능 적용

  - map : 모든 요소에 접근하여 제어    //  map(callbackfn: (value: T, index: number, array: T[])

const arr = [1, 2, 3, 4, 5];
const newArr = arr.map(function(value, idx, arr) {
console.log(value, idx, arr);
return value;
});
console.log(`old array: ${arr}`);
console.log(`new array: ${newArr}`);

 

  - reduce : 모든 요소에 접근하여 제어   

          // reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[])

const arr = [1, 2, 3, 4, 5];
const result = arr.reduce(function(pv, cv, idx, arr) {
console.log(pv, cv, idx, arr);
return pv + cv;
});
console.log(`array: ${arr}`);
console.log(`result: ${result}`);

 

③ 합치기

  - join : 배열 ➔ 문자열    //  join(separator?: string)

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join('&');
console.log(result);

 

   - concat : 다수의 배열 ➔ 하나의 배열    //  concat(...items: ConcatArray[])

const foods = ['🍕', '🍣'];
const animals = ['🐋', '🐘'];
const newArray = foods.concat(animals);
console.log(newArray);

 

④ 분리

  - split : 문자열 ➔ 배열    //  split(string: string, limit?: number)

const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(', ')
console.log(result);
const result2 = fruits.split(', ', 2)
console.log(result2);

 

 

  - slice : 지정 요소가 삭제된 배열 생성    // slice(start?: number, end?: number)

      => 시작 인덱스와 끝 인덱스를 사이의 요소로 새로운 배열 생성

      => 원본 데이터 유지 (array 변함 없음)

const array = [1, 2, 3, 4, 5];
const result = array.slice(3)
console.log(result); // [4, 5]
const result2 = array.slice(3, 4)
console.log(result2); // [4]
const result3 = array.slice(0, 2)
console.log(result3); // [1, 2]

 

 

  - splice : 지정 요소가 삭제된 배열 생성    // splice(start: number, deleteCount?: number)

       => 시작 인덱스와 분리(삭제)시킬 요소의 개수 지정으로 새로운 배열 생성

       => 원본 데이터 수정

const array = [1, 2, 3, 4, 5];
const result = array.splice(2, 2)
console.log(array); // [1, 2, 5] - 원본 데이터 수정
console.log(result); // [3, 4] - 2번 인덱스 ~ 요소 2개

 

⑤ 정렬

  - sort : 요소 값을 기준으로 정렬    //  sort(compareFn?: (a: T, b: T) => number)

      => 원본 데이터를 정렬하고, 새로운 배열도 생성

const array = [1, 3, 4, 2];
const newArray = array.sort();
console.log(`old array: ${array}`);
console.log(`new array: ${newArray}`);

      => 비교 연산으로 역순 정렬

const orderArray = [1, 3, 4, 2];
orderArray.sort(function (next, prev) {
console.log(`next: ${next}, prev: ${prev}`);
console.log(`prev - next = ${prev - next}`);
return prev - next;
});
console.log(`ordered array: ${orderArray}`);

 

  - reverse : 인덱스를 기준으로 역순 정렬

const array = [1, 3, 4, 2];
const newArray = array.reverse();
console.log(`old array: ${array}`);
console.log(`new array: ${newArray}`);

 

 

[배열 연습문제 1] 반복문을 사용하여 배열 요소 중 최대값을 찾는 max() 함수 작성하기 (단, 배열의 요소는 0 보다 큰 정수)

    const max = function(array) {
      let output = 0;
      for(i=0;i<array.length;i++){
        if (output < array[i]) output = array[i]
      };
      return output;
    };
    console.log(max([1,2,3,4]));

 

[배열 연습문제 2] 처음과 마지막 요소의 위치 변경하기 (pop / shift / push / unshift) 

초기값 :  const array = [1,2,3,4,5]     출력값 : [5,2,3,4,1,]

    const array = [1,2,3,4,5];
    array.pop();
    array.push(1);
    array.shift();
    array.unshift(5);
    console.log(array);

 

[배열 연습문제 3] 점수가 90점인 1명(첫번째)의 학생 정보 찾아내기 (find)

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

    let result = students.find((value) => {
      return value.score >= 90;
    });
    console.log(result)

  </script>

 

 

[배열 연습문제 4] 수업에 등록(enrolled)되어 있는 모든 학생의 정보 찾아내기 (filter)

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

    let result = students.filter((value) => {
      return value.enrolled == true;
    });
    console.log(result)

  </script>

 

 

[배열 연습문제 5] 점수가 50점 미만인 학생이 있는지 확인하기 (some)

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

    let result = students.some((value) => {
      return value.score < 50;
    });
    console.log(result)

  </script>

 

 

[배열 연습문제 6] 주어진 배열 요소 중 첫번째와 두번째 요소를 제외한 새로운 배열 생성하기 - 원본 데이터 유지 (slice)

  <script>
    const array = [1,2,3,4,5];
    const result = array.slice(2);

    console.log(`result => ${result}`);
    console.log(`array => ${array}`);


  </script>

 

 

[배열 연습문제 7] 주어진 배열 요소 중 첫번째와 두번째 요소를 제외한 새로운 배열 생성하기 - 원본 데이터 수정 (splice)

  <script>
    const array = [1,2,3,4,5];
    const result = array.splice(2,3);

    console.log(`result => ${result}`);
    console.log(`array => ${array}`);

  </script>

 

[배열 연습문제 8] 정렬 연습문제 (sort) 

! hint ! 홀수는 오름차순, 짝수는 내림차순 정렬

입력값 : [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

출력값 : [1, 3, 5, 7, 9, 10, 8, 6, 4, 2]

  <script>
    const array = [6, 7, 8, 9, 10, 1, 2, 3, 4, 5];
    const newArray = array.sort((next, prev) => {
      if(next % 2 == 1) {
        if(prev % 2 == 1) return next - prev;
        else return -1;
      }
      if(next % 2 == 0) {
        if(prev % 2 == 0) return prev - next;
        else return 1;
      }
    });
    console.log(`${newArray}`);

  </script>

 

[배열 연습문제 9] 학생들의 점수만 요소로 가지는 새로운 배열 생성하기

 <script>
    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, 90),
    ];
    
    const scores = students.map(student => student.score);
    console.log(scores); 

  </script>

 

 

 

[배열 연습문제 10] 점수가 50점 이상인 학생의 이름을 결과와 같이 문자열로 출력하기

  <script>
    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, 90),
    ];
    
    const result = students.filter((v) => {
      return v.score >= 50;
    }).map((v) => {
      return v.name;
    })
    console.log(result); 

  </script>

 

 

 

728x90
반응형
Contents

📝 포스팅 주소를 복사했습니다 📝

이 글이 도움이 되었다면 공감 부탁드립니다👍