배열 API 정리
join
const fruits = ["apple", "banana", "orange"];
const result = fruits.join();
console.log(result);
결과 : "apple", "banana", "orange"
배열을 string으로 변환할 수 있는 것이다. 배열에 있는 모든 것을 더해서 string으로 리턴한다.
전달해준 separated를 통해서 각각 구분자를 넣어서 전달한다. (”,” )이라면 이렇게 구분자를 넣어줌
디폴트는 , 이렇게 구분해준다.
split
split은 총 두가지의 파라미터를 받는데, 하나는 ‘,’의 구분자이고 하나는 리밋이라는 파라미터로 2개만 전달받고 싶을 때 할 수 있다. 구분자는 필수 파라미터이고, 리밋 파라미터는 안해도 상관없다.
const fruits = "🍎, 🥝, 🍌, 🍒";
const result = fruits.split(",",2);
console.log(result);
결과 : [🍎, 🥝, 🍌, 🍒] 배열로 나타냄
reverse
const array1 = [1, 2, 3, 4, 5];
array1.reverse();
console.log(array1);
결과 : [5,4,3,2,1]
배열 안에 들어있는 아이템의 순서를 거꾸로 만들어준다.
배열 자체를 변화시키고 리턴값도 변화된 배열 자체를 리턴한다.
splice
const array2 = [1, 2, 3, 4, 5];
array2.splice(0, 2);
console.log(array2);
결과 : [3,4,5]
어디서부터 몇개를 지울지를 파라미터로 받으면 리턴해주는 값이다.
이건 배열 자체를 완전 수정해주는 것이다. 배열 자체가 3,4,5로 변했다.
slice
const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5);
console.log(result);
결과 : [3,4,5]
이것은 이제 result값이 [3,4,5] 이고 array 자체의 배열은 [1,2,3,4,5]로 그대로이다
slice 역시 원하는 부분만 골라 보여지게 할 수 있다. 여기서 2,5 로 해준 이유는 마지막은 -1 해야한다. 결론은 2부터 4까지 가져온다는 뜻
find
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),
];
const findstudent = students.find((student) => student.score === 90);
console.log(findstudent);
결과 : Student {name: '’C, age: 30, enrolled: true, score: 90}
find는 콜백함수를 받아 첫번째로 찾아진 요소를 리턴한다. 콜백함수가 트루가 되면 찾아지자마자 리턴한다.
배열에 들어있는 아이들 각각 다 찾아서 true가 된 3번째 학생이 true가 되고, 나머지 4,5는 보지도 않음
filter
const enrollstudent = students.filter((student) => student.enrolled === true);
console.log(enrollstudent);
결과 :
- 0: Student {name: 'A', age: 29, enrolled: true, score: 45}
- 1: Student {name: 'C', age: 30, enrolled: true, score: 90}
- 2: Student {name: 'E', age: 18, enrolled: true, score: 88}
무언가를 골라내어서 새로운 배열을 만드는 것이다.
map
const scored = students.map((student) => student.score);
console.log(scored);
결과 : [45, 80, 90, 66, 88]
mapping 이라고 한다 map 이라고 하는것은 배열에 들어있는 요소 한가지 한가지를 다른것으로 변환해주는 것을 말한다.
map은 배열을 거쳐서 함수를 통해서 다시 새로운 배열로 만들어진다.
some
const result = students.some((student) => student.score < 50);
console.log(result);
결과 : true
이렇게 some을 사용하면서 50점 아래인 것이 하나라도! 있으면 true를 리턴해주는 것이다.
every
const result = !students.every((student) => student.score >= 50);
console.log(result);
결과 : true
여기서는 every를 이용해서 모든~ 데이터들을 다 확인한다음에 모두 다 50점이 넘는 학생만있는게 아니라면 true를 한다는 뜻이다.
확실히 알아보기 힘들어서 every는 모든 데이터에 공통사항을 검사할때만 쓰는것이 좋다.
reduce / reduceRight(거꾸로)
const avg = students.reduce((acc, cur) => acc + cur.score),0);
console.log(avg / students.lenght);
배열을 하나하나 돌면서 무언가의 값을 누적할 때 사용하는 것이다.
이렇게 콘솔을 찍어보면 하나하나씩 누적되는 것을 알 수 있다.
const result = students.map((student) => student.score).filter(score => score>=50).join()
console.log(result);
이렇게 묶어서 사용할 수 있다. map으로 score만 가져온 다음 filter로 50점이 이상인 아이들만 filter해서 join으로 string으로 만든다.
값 : 45,80,90,66,88
sort
const result = students.map((student) => student.score).sort((a,b)=>a-b).join()
console.log(result);
sort 중 파라미터 값인 a, b는 이전 index 다음 index 값들인데, a - b 면 만약에 a - b 였을 때 값이 -가 되면 오름차순 b - a 이면 내림차순으로 만들어 질 수 있는 것이다. 간단한 정렬이다.
'JavaScript' 카테고리의 다른 글
javascript 비동기 프로그래밍 - 콜백(callback) 이해하기 (0) | 2022.09.16 |
---|---|
javascript JSON 개념 정리와 활용 방법 및 유용한 사이트 공유 (0) | 2022.09.16 |
javascript 배열 (0) | 2022.09.15 |
javascript 오브젝트(object) (0) | 2022.09.15 |
javascript class와 오브젝트의 차이점, 객체지향 언어 클래스 정리 (0) | 2022.09.15 |