하다보니
유용한 10가지 배열 함수들. array apis 총정리 본문
// Q1. make a string out of an array
{
const fruits = ["apple", "banana", "orange"];
//구분자가 있어도 되고 없어도 된다.기본은 ,이다.
//배열의 모든 item을 string으로 나타내준다.
let result = fruits.join("^");
console.log(result); //apple^banana^orange
}
// Q2. make an array out of a string
//문자열 배열로 만들기
//seperator와 limit을 인자로 받을 수 있다.
//seperator는 필수, limit은 선택
{
const fruits = "🍎, 🥝, 🍌, 🍒";
result = fruits.split(",", 2);
console.log(result); // ['🍎', ' 🥝']
}
// Q3. make this array look like this: [5, 4, 3, 2, 1]
//배열 거꾸로 출력
//배열 자체도 변화시키고 그 값을 리턴한다.
{
const array = [1, 2, 3, 4, 5];
result = array.reverse();
console.log(result); //[5, 4, 3, 2, 1]
console.log(array); //[5, 4, 3, 2, 1]
}
// Q4. make new array without the first two elements
//splice는 어디서부터 몇개를 지울것인지.
//배열 자체에서 데이터를 삭제
//시작 위치, 삭제할 원소 개수를 인자로 받음
{
const array = [1, 2, 3, 4, 5];
//splice는 배열을 새로 만들어야 한다.
result = array.splice(0, 2);
console.log(result); //[1, 2]
console.log(array); // [3, 4, 5]
//slice를 이용해서 원하는만큼 자를 수 있다.
//start와 end를 사용한다. end는 포함하지 않는다.
//원래의 배열은 변화 없다.
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는 처음 true가 나오면 해당하는 조건의 요소를 리턴
{
result = students.find((student) => student.score === 90); //90점인 학생 나오면 리턴되고 멈춘다.
console.log(result.name);
}
// Q6. make an array of enrolled students
//filter를 이용해서 원하는 것만 가져올 수 있다.
{
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은 콜백함수 거치면서 새로운 값으로 매핑된 것.
//콜백함수에서 리턴된 값으로 대체.
//콜백함수로 전달되는 인자는 최대한 이해하기 쉽게 쓰는 것이 중요하다.
{
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
//some은 배열 안에 해당 콜백함수가 true인지 아닌지 확인해주는것
//해당 조건을 만족하는 원소가 하나라도 있는지 t/f 출력
{
result = students.some((student) => student.score < 50);
console.log(result);
//every - 해당 조건을 배열의 모든 원소가 만족하는지 t/f 출력
result = !students.every((student) => student.score >= 50);
console.log(result);
}
// Q9. compute students' average score
//reduce는 원하는 시작점부터 배열의 모든 값을 돌면서 값을 누적하는 것.
//cur은 배열 원소 하나씩 전달.
//prev는 리턴의 값 순차적으로 prev인자로 전달.
//initial 값을
//reduceRight은 배열의 제일 뒤에서부터 시작.
{
result = students.reduce((prev, cur) => prev + cur.score, 0);
console.log(result / students.length);
}
// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
result = students
.map((student) => student.score)
.filter((score) => score >= 50)
.join();
console.log(result); //80,90,66,88
}
// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
//sort는 이전값과 현재값 전달. -1 리턴시 뒤의 값이 더 크다고 간주. 오름차순
{
const result = students
.map((student) => student.score)
.sort((a, b) => a - b)
.join();
console.log(result);
}
참고 : 드림코딩 by 엘리
'프로그래밍 언어 > JavaScript' 카테고리의 다른 글
비동기 처리의 시작 콜백 이해하기 (0) | 2022.01.21 |
---|---|
JSON (0) | 2022.01.18 |
object (0) | 2022.01.16 |
[JavaScript]배열 (0) | 2022.01.15 |
[JavaScript]Class 와 Object 차이, 객체지향 언어 클래스 정리 (0) | 2022.01.14 |