오늘은 드림코딩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)
join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
let fruits = ['apple', 'banana', 'orange']
fruits.join() //'apple,banana,orange'
fruits.join("") //'applebananaorange'
fruits.join("&") // 'apple&banana&orange'
split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.
let basket = 'apple, banana, orange'
basket.split(",") // [ 'apple', ' banana', ' orange' ]
basket.split() // [ 'apple, banana, orange' ]
basket.split(",",2) // [ 'apple', ' banana' ]
reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.
array = [1,2,3,4,5]
array.reverse() // [ 5, 4, 3, 2, 1 ]
array // [ 5, 4, 3, 2, 1 ] 배열 자체가 바뀜!!!!!
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),
];
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가 뜨는 요소의 값을 반환한다.const result = students.find((student)=> student.score === 90)
Object {
age: 30,
enrolled: true,
name: "C",
score: 90
}
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}
}
]
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 ]
some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0; //true
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
const low50every = !students.every((student)=> student.score>=50)
low50every // true
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