배열(array)

Sunwoo·2021년 4월 28일
0

배열

객체는 특성(속성, 행위)들을 가지고 있다. 배열은 여러 데이터를 가지고 있다. 비슷한 타입의 오브젝트를 묶어둔 것을 자료구조라고 한다.

자바스크립트는 동적 언어(Dynamically typed language)이기 때문에 다양한 타입을 한 배열에 담을 수 있다. 그러나 권장되지 않는다.

// 1. Declaration
const arr1 = new Array();
const arr2 = [1, 2];

// 2. Index postion
const fruits = ['🍎', '🍌'];
console.log(fruits); // ["🍎", "🍌"] 뿐만 아니라 length와 proto가 포함
console.log(fruits[fruits.length - 1]); // 가장 마지막 데이터 "🍌"

// 3. Looping over an array
for (let i=0; i<fruits.length; i++) {
    console.log(fruits[i]);
}

for (let fruit of fruits) {
    console.log(fruit);
}

fruits.forEach(function (fruit, index, array) {
    console.log(fruit); // value
    console.log(fruit, index); // index
    console.log(fruit, index, array); // 배열전체(보통 안씀)
});
// 위를 애로우 펑션으로 하면
fruits.forEach((fruit) => console.log(fruit));

// 4. Addtion, deletion, copy
// push는 뒤에 붙인다
fruits.push('🍓', '🍑');
console.log(fruits); // (4) ["🍎", "🍌", "🍓", "🍑"]
// pop은 마지막 아이템을 뺀다.
fruits.pop();
fruits.pop();
console.log(fruits); // (4) ["🍎", "🍌"]
//unshift은 앞에 넣는다.
fruits.unshift('🍇');
console.log(fruits); // (3) ["🍇", "🍎", "🍌"]
//unshift은 앞에 뺀다.
fruits.shift();
console.log(fruits); // (2) ["🍎", "🍌"]

fruits.push('🍇', '🍓', '🍑');
console.log(fruits); // ["🍎", "🍌", "🍇", "🍓", "🍑"]

fruits.splice(1, 1); // index 1부터 1개까지를 뺀 나머지
console.log(fruits); // ["🍎", "🍇", "🍓", "🍑"]
fruits.splice(1, 1, '🍉'); // index 1부터 1개까지 지워진 자리에 추가
console.log(fruits); // ["🍎", "🍉", "🍓", "🍑"]
//concat은 두개의 배열 합쳐 하나로 한다.
const fruits2 = ['🍈', '🍆'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits); // (6) ["🍎", "🍉", "🍓", "🍑", "🍈", "🍆"]

// 5. Searching
console.log(fruits.indexOf('🍎')); // 0
console.log(fruits.indexOf('🍌')); // -1(없음)
console.log(fruits.includes('🍎')); // true
console.log(fruits.includes('🍖')); // false(없음)
fruits.push('🍎');
console.log(fruits.indexOf('🍎')); // 0 (여러개 중에 먼저)
console.log(fruits.lastIndexOf('🍎')); // 4 (여러 개중에 마지막)

배열 api에서 shift는 pop, push보다 느리다. 앞에 있는 값을 변경한다는 것은 배열 전체를 변경하는 작업이기 때문.

1-10번까지 문제 풀어보기 (유용한 배열 api 배우기)

  1. 배열의 모든 요소를 string으로 받아오기
{
  const fruits = ['apple', 'banana', 'orange']; 
  const result = fruits.join(); 
  console.log(result); // apple,banana,orange
  const result = fruits.join('|'); 
  console.log(result); // apple|banana|orange
}

join(separator?: string): string;은 separator(구분자)를 받는데 리턴을 string으로 해준다.

  1. String을 배열로 변경하기
{
  const fruits = '🍎, 🍇, 🍓, 🍑';
  const result = fruits.split(',');  // 구분자로 나눔
  console.log(result); // (4) ["🍎", "🍇", "🍓", "🍑"]
  const result = fruits.split(',', 2); // limit 옵션 값 넣을 수 만큼
  console.log(result); // (2) ["🍎", "🍇"]
  const result = fruits.split(); // 구분자가 없을 경우 하나로 묶음
  console.log(result); // (1) ["🍎, 🍇, 🍓, 🍑"]
}

split(separator: string | RegExp, limit?: number): string[]; separator(구분자)나 정규표현식을 기준으로 리턴받을 배열의 사이즈를 지정하면 배열을 리턴한다.

  1. 배열 거꾸로 하기
{
  const array = [1,2,3,4,5];
  const result = array.reverse();
  console.log(result); // (5) [5,4,3,2,1]
  console.log(array); // (5) [5,4,3,2,1]
}

reverse()는 (원본)배열 자체를 변경시킨다.

  1. 배열 잘라내기
{
  const array = [1,2,3,4,5];
  const result = array.splice(0, 2);
  console.log(result); // (2) [1,2]
  console.log(array); // (3) [3,4,5]
  const result = array.slice(2, 5); // 인덱스 주의
  console.log(result); // (3) [3,4,5]
  console.log(array); // (5) [1,2,3,4,5]
}

splice()는 결과값으로 잘나낸 부분을 출력한다. 또한 원본 배열에도 영향을 준다.
slice()는 결과값으로 잘나낸 부분을 출력하지만 원본에 영향을 주지 않는다.

데이터 찾기

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. 배열 안에 점수(score)가 90점인 학생(객체)를 찾자.
{
  const result = students.find(function (student, index) {
    return student.score === 90; // 90점인 학생을 찾아나감
  });
  console.log(result); // student {... score: 90...}
  const result = students.find((student) => student.score === 80);
  console.log(result); // student {... score: 80...}
}

find() 존재할 경우 true, 없으면 undefined

  1. 수업에 등록(enrolled)된 학생들을 찾아서 배열로 만들기
{
  const result = students.filter((student) => student.enrolled);
  console.log(result); // (3) [Student, Student, Student]
}

filter()는 조건을 걸어서 해당되는 것들을 반환해준다.

  1. 배열의 담긴 학생들의 점수를 두배로 해서 배열로 출력
{
  const result = students.map((student) => student.score * 2);
  console.log(result);
}

map()은 각각의 값을 새로운 각각의 배열로 만들어준다. 이렇게 각각에 연결되는 것을 매핑이라고 한다.

  1. 배열 안의 학생들의 점수가 50점 미만이 있는지?
{
  const result = students.some((student) => student.score < 50 );
  console.log(result); // true (or처럼 사용)
  const result2 = students.every((student) => student.score < 50 );
  console.log(result2); // false (and처럼 사용)
}

some()은 해당 값이 있는지 없는지 확인한다. 배열 중에 해당 되는 요소가 하나라도 있으면 true가 된다. 반대로 every()는 모든 요소가 충족되어야 true이다.

  1. 학생들의 평균 점수를 구하기 (모든 값을 누적계산 후 학생 수로 나누기)
{
  const result = students.reduce((prev, curr) => {
    console.log('-------');
    console.log(prev);
    console.log(curr);
    return prev + curr.score; // 다음 호출의 prev으로 전달
  }, 0) // 0은 초기값
  console.log(result / students.length); //평균
}

{ // 데이터 누적을 역순으로 불러드림
  const result = students.reduceRight((prev, curr) => prev + curr.score, 0)
  console.log(result / students.length); //평균
}

reduce는 배열의 값이 여러개 있을 때, 콜백에서 리턴하는 값을 이전 값으로 하고 현재 값을 사용해서 순차적으로 넘어간다. 이는 누적과 같은 곳에서 사용하며, 이전 값에 현재 값을 더하는 값을 리턴하는 것으로 누적하는 방식으로 처리한다. reduceRight()은 반대로 처리한다.

  1. 학생들의 점수에서 50점 이상인 값들을 String으로 출력
{
  const result = students
    .map((student) => student.score) // 점수만 빼냄
    .filter((score) => score >= 50) // 50점 이상만 반환
    .join(); // 배열의 값을 string으로 
  console.log(result); // 80,90,66,88
}

+SORT(정렬)

{
  const result = students
    .map((student) => student.score)
    .sort((a, b) => a - b) //오름차순 (낮은것부터)
    //.sort((a, b) => b - a) //내림차순 (높은것부터)
    .join();
  console.log(result);
}
profile
한 줄 소개 너무나 어려운 질문이다.

0개의 댓글