Javascript | 배열 함수들

Ssss·2021년 2월 12일
0

Javascript

목록 보기
3/3
post-thumbnail

오늘은 드림코딩by엘리의 "자바스크립트 9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6)"를 보며 유용한 배열 함수들을 정리해보았다. (https://www.youtube.com/watch?v=3CUjtKJ7PJg&ab_channel=%EB%93%9C%EB%A6%BC%EC%BD%94%EB%94%A9by%EC%97%98%EB%A6%AC)

1. join()

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

let fruits = ['apple', 'banana', 'orange']
fruits.join() //'apple,banana,orange'
fruits.join("") //'applebananaorange'
fruits.join("&") // 'apple&banana&orange'
  • 아무것도 안썼을경우, 배열안에 있는 모든 요소들을 하나의 string으로 엮어버린다.
  • ("")로 했을경우 separator를 none으로 지정하기 때문에 모든 요소들이 space없이 붙어버린다.
  • ("&")라는 separator를 지정해주면 하나의 string안에 요소들이 &로 엮인다.

2. split()

split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

let basket = 'apple, banana, orange'
basket.split(",") // [ 'apple', ' banana', ' orange' ]
basket.split() // [ 'apple, banana, orange' ]
basket.split(",",2) // [ 'apple', ' banana' ]
  • split()은 string을 array로 바꿔준다
  • ()일 경우, 그대로 배열안에 들어간다
  • (",")일 경우, 모든 요소가 ""로 묶인다
  • (",",2)처럼 limit을 정해줄 경우, 끊어진 문자열의 최대 개수만 나타낸다.

3. reverse() ⛔️ 배열 자체가 바뀜! ⛔️

reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

array = [1,2,3,4,5]
array.reverse() // [ 5, 4, 3, 2, 1 ]
array // [ 5, 4, 3, 2, 1 ] 배열 자체가 바뀜!!!!!
  • 순서가 바뀐다. 배열 자체가 바뀐다는것을 유의해서 써야한다.

4. slice() & splice() ⛔️ 배열 자체가 바뀜! ⛔️

https://velog.io/@hi-yjs/Javascript-.slice-vs-.splice

array1= [1,2,3,4,5];
array1.slice(2) // [ 3, 4, 5 ]
array1 // [ 1, 2, 3, 4, 5 ]

array1.splice(0,2) // [ 1, 2 ]
array1 // [ 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),
];

5. find()

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

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
  • find()는 array를 쭉 돌면서 각 요소(element)를 하나하나 확인하다가 처음 true가 뜨는 요소의 값을 반환한다.

🍎 90점 받은 학생 찾기

const result = students.find((student)=> student.score === 90)
  Object {
  age: 30,
  enrolled: true,
  name: "C",
  score: 90
}

6. filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
  • filter()는 array를 쭉 돌면서 true를 반환하면 요소를 유지하고 false를 반환하면 버린다.

🍎 등록한 학생 찾기

const enrolled = students.filter((student)=> student.enrolled === true)
[
  Student {
    name: 'A',
    age: 29,
    enrolled: true,
    score: 45 }
  },
  Student {
    name: 'C',
    age: 30,
    enrolled: true,
    score: 90 }
  },
  Student {
    name: 'E',
    age: 18,
    enrolled: true,
    score: 88}
  }
]

7. map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

  • map()은 array를 돌면서 각각 함수를 실행 시키고 그 함수의 반환값으로 새로운 배열을 만든다
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]

🍎 학생들 점수 배열 만들기

const scores = students.map((student)=>student.score)
[ 45, 80, 90, 66, 88 ]

8. some() & every()

some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.

const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0; //true
  • 한 요소라도 true가 되면 통과~

🍎 50점이하의 점수를 받은 학생이 있는지 찾기

const low50 = students.some((student)=> student.score <50)
low50 // true

every() 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다.

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));//true

🍎 50점이하의 점수를 받은 학생이 있는지 찾기

const low50every = !students.every((student)=> student.score>=50)
low50every // true

9. reduce()

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다. 다음 네 가지 인수를 받는다.

  • accumulator(initialValue): 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출
  • currentValue: 처리할 현재 요소
  • currentIndex(optional): 처리할 현재 요소의 인덱스, initialValue를 제공한 경우 0, 아니면 1부터 시작합니다
  • array(optional): reduce()를 호출한 배열

이게 무슨 말이고.... 예제를 살펴보자

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

따로 블로그정리해야겠다!!!🔎 일단은 이렇게 이해하고 넘어가고,,,

🍎 학생들 점수 평균값 찾기

  const total = students.reduce((prev, curr)=> prev+curr.score,0)
  total/students.length //73.8
profile
Front-end Developer 👩‍💻

0개의 댓글