Javascript-16 (splice, slice, find, filter)

Patrick·2021년 4월 27일
0

Javascript

목록 보기
16/18
post-thumbnail

저번 시간에 이어서 배열에서 사용되어지는 API들에 대해서 알아보려고 한다.


splice

  • 배열에서 어디에서부터 어디까지를 지울지 정하면 삭제해주는 api라고 할 수 있다.
/* Q : : 첫번째, 두번째 제외한 나머지 부분만 뽑아서 새로운 배열 만들기 */

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

이처럼 splice를 하고 나면 원래 array에도 영향을 받게 된다.
즉, splice는 새로운 배열을 만드는 것이 아니다.

slice

  • splice처럼 자르는 형태이므로 비슷해서 헷갈릴 수 있지만, splice와 다르게 원래 array는 영향을 받지 않는다!
/* Q : : 첫번째, 두번째 제외한 나머지 부분만 뽑아서 새로운 배열 만들기 */

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

이처럼 slice를 하고 나면 array를 다시봐도 그대로 원형을 유지하고 있다.
즉, 원래 형태를 유지하면서 원하는 범위만 return해서 받아오고 싶을 때 사용 할 수 있다.

find

  • 조건을 걸어서 Array 안에서 똑같은 것을 찾을 때 사용한다.
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 result = students.find((student, index) => {
  return student.score === 90;
});
console.log(result);
  • 위에서부터 차례대로 찾다가 true가 나오면(똑같은 것이 나오면) 찾는 것을 멈추게 된다(return 된다).

filter

  • 배열 안에 있는 여러가지 내용 중 원하는 데이터만 걸러서 새로운 배열을 전달 해 줄 때 사용된다
const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

const smallAnimals = animals.filter((item) => {
  return item.size === 'medium';
})

console.log(smallAnimals);

이런 식으로 medium size 인것만 찾을 수도 있고, 반대로 삭제를 할 때도 사용된다.

const animals = [
  { name: 'lion', size: 'big', isAggressive: true, weight: 300 },
  { name: 'monkey', size: 'medium', isAggressive: true, weight: 18 },
  { name: 'rat', size: 'small', isAggressive: false, weight: 5 },
]

const smallAnimals = animals.filter((item) => {
  return item.size !== 'medium';
})

console.log(smallAnimals);

이렇게 !== 같지 않다를 사용해주면 그것만 뺄 수도 있다!
(장바구니 등에서 활용을 해볼 수 있다)

profile
예술을 사랑하는 개발자

0개의 댓글