Script

배열 api 본문

Javascript

배열 api

scripter. 2022. 6. 17. 14:11

1.join

배열안에 있는 것들을 하나의 문자열로 만든다

{
  const  fruits = ['apple','banana','orange'];
  const result = fruits.join();//()안에는 사이사이에 들어갈 것을 입력
                               //ex)fruits.join(|)-apple | banana | orange
  console.log(result);//apple,banana,orange
}

 

2.split

하나의 문자열을 배열로 만든다

{
  const fruits ='🍎,🥝,🍌,🍒';
  const result =fruits.split(',');//()안에는 무엇을 기준으로 쪼갤것인지를 입력
                                  //fruits.split(',',2)- (2) ['🍎', '🥝']
  console.log(result);//['🍎', '🥝', '🍌', '🍒']
}

 

3.reverse

배열안에 있는 item들의 순서를 역으로 바꿈

{
  const array = [1,2,3,4,5];
  const result = array.reverse();
  console.log(result);//(5) [5, 4, 3, 2, 1]
}

 

4.slice

{
  const array = [1,2,3,4,5];
  const result=array.slice(2,5);//index2부터 index5의 전값까지 출력(index2,3,4)
  console.log(result);//(3) [3, 4, 5]
  console.log(array);//(5) [1, 2, 3, 4, 5]
  //slice는 result의 값만 바꿀뿐 배열 자체값까지 바꾸어 버리진 않는다
}

 

5~11.공통 

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

배열내에서 특정 조건을 가진 아이템을 찾고 싶을 경우 사용

//ex) 점수가 90점 이상인 학생을 찾고 싶을때
{
  const result = students.find((student) =>student.score === 90);
  console.log(result);
}

 

6.filter

배열중 true인 값들을 모아서 새로운 배열로 만든다

//ex)enrolled가 true인 student들로 새로운 배열을 만들고 싶을때
{
  const result = students.filter((student)=>student.enrolled);
  console.log(result);
}

 

7.map

원래있던 배열의 아이템들을 특정 아이템들로 대체한다

//ex)sudent 배열을 student의 score만 들어있는 배열로 대체하고 싶을때
{
const result = students.map((student) => student.score);//student.score*2 => *2된 값이 배열에 들어간다
console.log(result);
}

 

8.some

특정 조건에 해당하는 item이 있는지 없는지 확인할떄 사용(결과는 boolean값)

//ex)score가 50보다 작은 학생이 있는지 없는지 알고싶을때
{
const result = students.some((student) => student.score <50);
console.log(result);//true

//every-배열의 모든조건이 조건을 충족해야만 true 출력
const result2 = students.every((student) => student.score <50);
console.log(result2);//false
}

 

9.reduce

누적계산

//initialvalue에 집어넣는 값으로 계산을 시작
//0+A의 점수 -> (0+A)+B의 점수 -> ((0+A)+B의 점수)+C의 점수...이런식
//prec에는 return된 값이 전달되고 curr에는 배열의 값이 순차적으로 전달된다
//ex)학생들 점수의 총합을 구하고 싶을때
{
const result = students.reduce((prev,curr) =>prev +curr.score,0);
console.log(result);//369
}

 

10.여러개 묶어서 사용하는 경우

{
  const result= students
  .map((student)=>student.score)
  .filter((score)=>score >=50)
  .join();
  console.log(result);
}

 

11.sort-분류할때 사용

 

{
  const result = students
  .map((student)=>student.score)
  .sort((a,b)=>a-b)//오름차순
              //b-a ->오름차순
  .join();
  console.log(result);//(5) [45, 66, 80, 88, 90]
}

'Javascript' 카테고리의 다른 글

Callback  (0) 2022.06.17
JSON  (0) 2022.06.17
배열  (0) 2022.06.15
object란?  (0) 2022.06.14
class와 object  (0) 2022.06.14
Comments