Array

Dasol Kim·2022년 2월 20일
0
post-thumbnail

본 포스팅은 유튜브 드림코딩의 강좌를 수강한 후 필자가 홀로 복습한 내용과 함께 재구성하여 작성되었다.


prototype-based의 객체 지향 언어인 자바스크립트의 Array 역시 함수의 일종으로 여러 가지 멤버 변수와 메소드 등의 api가 미리 정의된 Prototype Object를 가지고 있어서 배열의 객체들은 이들을 상속하게 된다. 이러한 기본 지식을 바탕으로 이번 포스팅에서는 1. Javascript 언어에서 배열의 특징2. 배열 프로토타입에 정의된 api들을 정리해보려고 한다.

프로토타입 기반의 객체 지향 언어로서 Javascript의 특징을 자세히 다룬 저번 포스팅을 참조하기를 바란다.



Javascript 배열의 특징

배열 생성 방법

배열을 생성하는 방법은 크게 세 가지로 나눌 수 있다.

// 'fruits' array created using array literal notation.
const fruits = ['Apple', 'Banana'];
console.log(fruits.length);
// 2

// 'fruits' array created using the Array() constructor.
const fruits = new Array('Apple', 'Banana');
console.log(fruits.length);
// 2

// 'fruits' array created using String.prototype.split().
const fruits = 'Apple, Banana'.split(', ');
console.log(fruits.length);
// 2

객체를 생성할 때 object literals를 쓰거나 Object() constructor을 이용했던 것처럼, array 역시 array literalsArray() constructor을 이용할 수 있다. 지난 시간에 constructor function을 공부했듯이, 자바스크립트에서 함수, 배열을 포함한 모든 객체는 클래스 없이도 constructor을 이용해서 생성할 수 있다.
세번째 방법은 String 객체의 prototype에 속한 메소드인 split()을 이용해서 배열 객체를 생성하는 방법이다.

prototype에 대해 얘기를 했으니 배열의 prototype object에 대한 스크린샷을 확인해보자.

예상했던 것처럼 prototype object는 constructor(), 프로토타입 링크([[Prototype]]: Object), 그리고 다른 prototype 속성들을 확인할 수가 있다. prototype 속성 중 하나인 length는 배열의 크기를 반환하며, 위의 배열 생성 방법에 대한 코드에서 사용한 것을 확인할 수 있다.

배열 초기화 시, 크기와 타입을 지정하지 않아도 된다.

전형적인 객체 지향 언어인 Java 에서는 배열을 생성할 때에는 int arr[] = new arr[5]; 와 같이 배열의 크기(5)와 배열에 들어가는 원소의 타입(int)을 지정해주어야 한다. 그러나 Dynamically Typed Language인 javascript에서는 두 가지를 지정해주지 않아도 된다.

배열 역시 객체의 일종으로, 할당을 통해 얕은 복사를 하게 된다.

const arr1 = [1, 2];
const arr2 = arr2;
arr2[0] = 3;
console.log(arr1[0]); // 3 



Array API

Looping over an array

// print all fruits
const fruits = ['🍎', '🍌'];
// a. for
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

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

// c. forEach
fruits.forEach((fruit) => console.log(fruit));

array를 looping하는 방법은 위에처럼 크게 기본적인 for문, for과 of의 조합, 혹은 Array의 인스턴스 메소드 중 하나인 forEach를 사용하는 것이다.

Insertion, deletion, copy

// push: add an item to the end
fruits.push('🍓', '🍑');
console.log(fruits); // ['🍎', '🍌', '🍓', '🍑']

// pop: remove an item from the end
const poped = fruits.pop();
console.log(poped) // '🍓'
fruits.pop();
console.log(fruits); // ['🍎', '🍌']

// unshift: add an item to the beginning
fruits.unshift('🍓', '🍋');
console.log(fruits); // ['🍓', '🍋', '🍎', '🍌']

// shift: remove an item from the beginning
fruits.shift(); 
fruits.shift(); 
console.log(fruits); // ['🍎', '🍌']

// note!! shift, unshift are slower than pop, push

// splice: remove an item by index position
fruits.push('🍓', '🍑', '🍋');
console.log(fruits); // // ['🍎', '🍌', '🍓', '🍑', '🍋']
fruits.splice(1, 1);
console.log(fruits); //  ['🍎', '🍓', '🍑', '🍋']
fruits.splice(1, 0, '🍏', '🍉');
console.log(fruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋']

// concat: combine two arrays
const fruits2 = ['🍐', '🥥'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);  // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋', '🍐', '🥥']

Searching

// indexOf: find the index
console.log(fruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋']
console.log(fruits.indexOf('🍎')); // 0
console.log(fruits.indexOf('🍉')); // 2
console.log(fruits.indexOf('🥥')); // -1

// includes
console.log(fruits.includes('🍉')); // true
console.log(fruits.includes('🥥')); // false

// lastIndexOf
fruits.push('🍎');
console.log(fruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋', '🍎']
console.log(fruits.indexOf('🍎')); // 0
console.log(fruits.lastIndexOf('🍎')) // 6
console.log(fruits.lastIndexOf('🥥')); // -1

Other APIs with Quiz

// Q1. make a string out of an array
{
    const fruits = ['apple', 'banana', 'orange'];
    const result = fruits.join(',');
    console.log(result); // apple,banana,orange
  }
  
  // Q2. make an array out of a string
  {
    const fruits = '🍎, 🥝, 🍌, 🍒';
    const result = fruits.split(',');
    console.log(result); // ['🍎', ' 🥝', ' 🍌', ' 🍒']
  
  // Q3. make this array look like this: [5, 4, 3, 2, 1]
  // reverse(): This method mutates the array and returns a reference to the same array.
  {
    const array = [1, 2, 3, 4, 5];
    const result = array.reverse();
    console.log(result); // [1, 2, 3, 4, 5]
    console.log(array); // [1, 2, 3, 4, 5]
  }
  
  // Q4. make new array without the first two elements
  // slice(): Returns a copy of a section of an array.
  {
    const array = [1, 2, 3, 4, 5];
    const result = array.slice(2, 5);
    console.log(result); // [3, 4, 5]
    console.log(array); // [1, 2, 3, 4, 5]
  }
  
  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
  // find():  Returns the value of the first element in the array where predicate is true, and undefined otherwise.
  {
    const result = students.find((student) => student.score === 90);
    console.log(result); // Student {name: 'C', age: 30, enrolled: true, score: 90}
  }
  
  // Q6. make an array of enrolled students
  // filter(): Returns the elements of an array that meet the condition specified in a callback function.
  {
    const result = students.filter((student) => student.enrolled);
    console.log(result);
  }
  
  // Q7. make an array containing only the students' scores
  // result should be: [45, 80, 90, 66, 88]
  // map(): Calls a defined callback function on each element of an array, and returns an array that contains the results.
  {
    const result = students.map((student) => student.score);
    console.log(result); // [45, 80, 90, 66, 88]
  }
  
  // Q8. check if there is a student with the score lower than 50
  {
    const result = students.some((student) => student.score < 50);
    console.log(result); // true
  
    const result2 = !students.every((student) => student.score >= 50);
    console.log(result2); // true
  }
  
  // Q9. compute students' average score
  // reduce(): Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  {
    const result = students.reduce((prev, curr) => prev + curr.score, 0);
    // 0 + 45 = 45
    // 45 + 80 = 125
    // 125 + 90 = 215
    // 215 + 66 = 281
    // 281 + 88 = 369
    console.log(result / students.length); // 73.8
  }

  // 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);
  }
  
  // Bonus! do Q10 sorted in descending order
  // result should be: '45, 66, 80, 88, 90'
  // sort(): This method mutates the array and returns a reference to the same array.
  {
    const result = students
      .map((student) => student.score)
      .sort((a, b) => b - a)
      .join();
    console.log(result); // 90,88,80,66,45
  }
}

0개의 댓글