[JS] Array Api

박영준·2020년 9월 22일
0

Javascript 기초

목록 보기
7/7

Array api

1. join

  • 배열을 문자열로 변환해준다.
  • .join() 괄호안에 넣은 문자로 구분자를 표시한다.
// Q1 make a string out of an array
  const fruits = ['apple', 'banana', 'orange'];
  const result = fruits.join('|');
  console.log(result); // apple | banana | orange

2. split

  • 문자열을 배열로 변환해준다.
  • .split(',', number) split은 꼭 구분자,로 구분지어 줘야하고 뒤에 나오는 number(optional)는 몇개를 출력하는지를 나타낸다.
// Q2 make an array out of a string
  const fruits = '🍎, 🥝, 🍌, 🍒';
  const result = fruits.split(',', 3);
  console.log(result); // '🍎, 🥝, 🍌,`

3. reverse

  • 배열을 거꾸로 변환해준다.
  • .reverse()
// Q3 make this array look like this: [5, 4, 3, 2, 1]
  const array = [1, 2, 3, 4, 5];
  const result = array.reverse();
  console.log(result);
  console.log(array); // reverse를 사용하면 array 자체가 바뀌니 유의

4. slice

  • 배열에서 원하는 부분만 받아와서 새로운 배열을 만든다.
  • .slice(number1, number2) number1은 start index, number2는 end index, end index는 배제 되기 때문에 원하는값 +1
  • splice는 배열 자체를 변형, slice는 배열에서 원하는 부분만 return해서 받아오고 싶을때 사용
// Q4 make new array without the first two elements
  const array = [1, 2, 3, 4, 5];
  const result = array.slice(2, 5);
  console.log(array);
  console.log(result);

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

  • 첫번째로 찾아진 콜백함수가 true면 return한다. 찾지 못하면 undefined를 return한다. 배열에 있는 모든 요소가 호출되고 호출되어지는 콜백함수가 true를 리턴하면 함수를 멈추고 true가 된 요소를 return한다.
// Q5 find a student with the score 90
{
  console.clear();
  const result = students.find(function (student) {
    return student.score === 90;
  });
  console.log(result); 
  //Student {name: "C", age: 30, enrolled: true, score: 90}
}

6. filter

  • 콜백함수를 전달해서 콜백함수가 true인 값들만 모아 새로운 배열을 만드는 api
// Q6. make an array of enrolled students
{
  console.clear();
  const result = students.find(function (student) {
    return student.score === 90;
  });
  console.log(result); // Student A , Student C, Student E
}

7. map

  • 배열안에 들어있는 요소 하나하나를 다른것으로 변환해주는것을 말한다. 지정된 콜백함수를 호출하면서 각각의 배열안 요소들을 함수를 거쳐서 다시 새로운 값으로 변환하는 것이다.
// Q7. make an array containing only the students' scores
{
  const result = students.map((student) => student.score);
  console.log(result); // [45, 80, 90, 66, 88]
}

8. some,every

  • some: 배열의 요소중에서 콜백함수가 리턴이 true가 되는값이 있는지 없는지 확인해주는것이다. 어떤것이라도 하나 만족되는 값이 있는지 없는지 말이다.
  • every: 모든 값이 만족되는 값이 있는지 없는지 확인하는 것이다.
// Q8. check if there is a student with the score lower than 50
{
  const result = students.every((student) => student.score >= 30);
  console.log(result); // true
}

9. reduce

  • 콜백함수와 이니셜 요소를 전달할수 있다.
  • 콜백함수에서 리턴되는 값과 함께 누적된 결과값을 리턴한다.
  • curr 리턴값을 줘야한다. 안하면 prev값이 출력이 안된다. curr 리턴한 값이 다음에 호출 될때 prev로 연결 되어진다.
  • 이니셜 벨류를 전달하는 순간 이니셜 벨류부터 prev가 시작된다.
// Q9. compute students' average score
{
  const result = students.reduce(function (prev, curr) {
    return prev + curr.score;
  }, 0);
  console.log(result / 5); // 73.8
}

10. 함수형 프로그래밍

-apis 짬뽕가능, 묶어서 작성가능

// Q10. make a string containing all the scores
{
  const result = students
    .map((student) => student.score)
    .filter((score) => score >= 50)
    .join();
  console.log(result);
}

11. sort

  • 콜백함수에는 a,b 즉 이전값과 현재값이 전달이 되는데 만약 - 값을 리턴하게 되면 a가 b보다 작다고 간주하게 되서 정렬이 된다.
//Q11 sorted in ascending order
{
  const result = students
    .map((student) => student.score)
    .sort((a, b) => a - b)
    .join();
  console.log(result); //'45, 66, 80, 88, 90'
}
profile
React, React-Native Developer

0개의 댓글