본문 바로가기
핀테크 서비스 프론트엔드 개발자 취업 완성 2기/JS

[JS] 데이터 - Array (배열)

by flyda 2022. 4. 25.

1. index, indexing, element(item) 

const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

- index(인덱스) : 인덱스는 0부터 시작한다. 따라서 'apple'은 index = 0, 'banana'는 index=1이다! nubers의 1 또한 index =0이라는 것!! 

- indexing(인덱싱) : 배열 속의 데이터를 배열의 이름과 인덱스 번호로 접근할 수 있다. 예를 들면 numbers 배열 속의 데이터 '2'에 접근하고 싶다면 `numbers [1]`과 같이 그 배열의 이름과 인덱스 번호를 사용하면 된다. 

- element(요소) : 배열 속의 데이터를 element(요소)라고 부른다. 하지만 html의 요소와 구분을 위해서 item이라고도 한다!! 즉 'apple'은 fruits 배열의 element(요소) 혹은 item이다! 

 

본격적으로 배열을 배우기 전에 간단하게 mdn 문서를 살펴보자! 

Array.prototype.find()에서 있는 코드로 화살표 함수를 잠깐 복습을 해볼 것이다!! 

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

array1.find()는 메서드이다. 메서드를 잘 모르겠다면 공식 문서블로그 글을 참고하길 바란다. 

어떤 함수가 함수의 인수로 들어가 있을 때 그 함수를 callback함수, 줄여서 callback이라고 하는데, 지금 여기에서는 find 함수 안에 화살표 함수 (element => element > 10)가 콜백으로 들어가 있다. 

find()함수 안에서 호출된 화살표 함수 element => element > 10는 매개변수가 하나밖에 없어서 소괄호를 생략하고, 함수의 시작이 return으로 시작하기 때문에 return과 중괄호를 생략했다. 화살표 함수를 생략하지 않은 모양은 다음과 같다. 

const found = array1.find((element) => {
  return element > 10
});

console.log(found);
// expected output: 12

생략할 수 있는 것은 생략하여 간단하고 더 가독성을 높인 함수를 작성할 수 있다!

 

 

이제 본격적으로 배열에 많이 사용되는 함수를 살펴볼 것이다. 

2. Array.prototype.length

 

//.length
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

console.log(numbers.length)//5
console.log(fruits.length)//3
console.log([1,2,3].length)//3

console.log([].length)//0

마지막 줄과 같이 length를 통해서 배열이 비어있는지 아니면 요소를 가지고 있는지 체크를 많이 한다! 

 

3. Array.prototype.concat()

//.concat()
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

console.log(numbers.concat(fruits))  //[1, 2, 3, 4, 5, 'apple', 'banana', 'cherry']
console.log(numbers) //[1, 2, 3, 4, 5]
console.log(fruits) //['apple', 'banana', 'cherry']

concat함수는 배열을 합치지만, 원본 배열은 수정하지 않고 새로운 배열을 반환해준다. 

 

4. Array.prototype.forEach()

//.forEach() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

fruits.forEach(function (element, index, array) {
  console.log(element, index, array)
})

//apple 0 ['apple', 'banana', 'cherry']
//banana 1 ['apple', 'banana', 'cherry']
//cherry 2 ['apple', 'banana', 'cherry']

여기에서 매개변수의 이름은 자유롭게 작성이 가능하다. 그리고 index는 줄여서 i라고 표현해 줄 수 있고, array부분은 잘 사용하지 않는다. 

//.forEach() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

fruits.forEach(function (fruit, i) {
  console.log(fruit, i)
})

//apple 0 
//banana 1 
//cherry 2

forEach라는 메서드는 인수로 콜백을 사용할 수 있고, 그 콜백은 각각 반복되는 횟수(index)와 배열 데이터(element)를 매개변수로 제공하고 있다. forEach는 배열 데이터의 개수만큼 특정한 콜백 함수를 반복적으로 실행하는 데 사용되는 메서드이다. 

 

5. Array.prototype.map()

//.map() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.forEach(function (fruit, index) {
  console.log(`${fruit}-${index}`)
  //apple-0
  //banana-1
  //cherry-2
})
console.log(a) // undifined



const b = fruits.map(function (fruit, index) {
  return (`${fruit}-${index}`)
})
console.log(b) //['apple-0', 'banana-1', 'cherry-2']

forEach 메서드map 메서드는 둘다 배열에 들어있는 요소의 수만큼 반복적으로 callback을 실행한다. 

하지만 forEach 메서드는 실행되고 반환되는 부분이 없다. 그래서 변수에 담아서 출력해도 undefined가 출력된다. 

map 메서드는 다르다!! map 메서드는 callback에서 반환된 특정한 데이터를 기준으로 해서 그 데이터들의 모음인 새로운 배열을 메서드가 실행된 자리에서 반환해준다. 그래서 b에 할당이 되고 console.log(b)로 반환된 배열을 확인할 수 있다. 

map 메서드는 다음과 같이 객체를 활용해서 만들 수 있다. 

const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']
const b = fruits.map(function (fruit, index) {
  return {
    id : index,
    name : fruit
  }
})
console.log(b) //[{id: 0, name: 'apple'}, {id: 1, name: 'banana'}, {id: 2, name: 'cherry'}]

 

참고 ) 위에서 사용한 코드에서 callback 부분을 화살표 함수를 바꿀 수 있다.  일반함수와 화살표 함수의 차이점은 this 키워드 사용에서 나타난다. 이 코드에서는 this가 사용되지 않았기 때문에 화살표 함수로 바꿔서 작성할 수 있다. 작성된 코드는 다음과 같다.

//일반 함수 -> 화살표 함수
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.forEach((fruit, index) => {
  console.log(`${fruit}-${index}`)
})
console.log(a) 


const b = fruits.map((fruit, index) =>({
  id : index,
  name : fruit
}))
console.log(b)

 

6. Array.prototype.filter( )

//.filter() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = numbers.map(number => {
  return number < 3
})
console.log(a)//[true, true, false, false, false]

const b = numbers.filter(number => {
  return number < 3
})
console.log(b)//[1, 2]

filter 메서드는 배열의 수 만큼 콜백을 실행해서 반환 값이 true인 경우에만 새로운 배열에 하나씩 넣어준다. 

따라서 map 메서드의 경우 원본 배열과 길이가 같은 배열을 반환하지만,  filter 메서드의 경우 원본 배열의 길이와 반환된 배열의 길이가 다를 수 있다. 또 map 메서드와 filter 메서드는 원본에 영향을 주지 않고 새로운 배열을 반환한다. 

조금 더 정리한 코드는 다음과 같다!

//.filter() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = numbers.map(number => number < 3)
console.log(a)//[true, true, false, false, false]

const b = numbers.filter(number => number < 3)
console.log(b)//[1, 2]

console.log(numbers) //[1, 2, 3, 4, 5]

 

 

7.Array.prototype.find()Array.prototype.findIndex()

//.find(), .findIndex() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.find( fruit => {
  return /^b/.test(fruit)
})

console.log(a)//banana

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다. 만약 그런 요소가 없다면 undefined를 반환한다. 

find 매서드의 콜백에서 반환하는 식 `/^B/.test(fruit)`을 살펴보면 다음과 같다. 

/^B/는 정규표현식을 통해서 b로 시작하는(^) 문자데이터를 의미한다.  test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false로 반환한다. test()는 banana를 만나면 true를 반환한다. 

정규표현식에 대한 자세한 내용은 다음에 다루겠다. 혹시 궁금하다면 링크된 mdn 문서나 박영웅강사님의 블로그를 참고하기를 바란다. 

//.find(), .findIndex() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.find( fruit => {
  return /^b/.test(fruit)
})

console.log(a) //banana

const b = fruits.findIndex( fruit => {
  return /^b/.test(fruit)
})

console.log(b) //1

이 코드를 간소화 하면 다음과 같다. 

//.find(), .findIndex() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a = fruits.find( fruit => /^b/.test(fruit))

console.log(a) //banana

const b = fruits.findIndex( fruit => /^b/.test(fruit))

console.log(b) //1

 

8.Array.prototype.includes()

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별한다. 

//.find(), .findIndex() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

const a =numbers.includes(3)

console.log(a) //true

const b = fruits.includes('Flyda')

console.log(b) //false

 

9. Array.prototype.push()Array.prototype.unshift()

두 메서드는 모두 배열을 수정한다! 

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다. 

unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환한다. 

//.push(), .unshift() 
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

numbers.push(6)
console.log(numbers)// [1, 2, 3, 4, 5, 6]

numbers.unshift(0)
console.log(numbers)// [0, 1, 2, 3, 4, 5, 6]

 

10. Array.prototype.reverse()

//.reverse()
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

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

fruits.reverse()
console.log(fruits)//['cherry', 'banana', 'apple']

 

reverse() 메서드는 배열의 순서를 반전한다. 즉 뒤집어서 반환을 한다!  첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 된다.

 

11. Array.prototype.splice()

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다. 

//.splice()
const numbers =  [1, 2, 3, 4, 5]
const fruits = ['apple', 'banana', 'cherry']

numbers.splice(2,1) // index 번호 2번에서 item을 1개 지우라는 말!
console.log(numbers)//[1, 2, 4, 5]

numbers.splice(2,0, 999)  // index 번호 2번에서 item을 0개를 지우고 999를 끼워넣어라!
console.log(numbers)//[1, 2, 999, 3, 4, 5]

numbers.splice(2, 1, 999) //index 2번에서 item을 1개 지우고 999를 넣어라!! 
console.log(numbers)//[1, 2, 999, 4, 5]

fruits.splice(2, 0, 'orange')
console.log(fruits) //['apple', 'banana', 'orange', 'cherry']

해당 인덱스 번호에서 아이템을 지우거나 끼워 넣는 용도로 사용한다!! 

 

댓글