[개념] 자바스크립트 / 배열의 메서드(2)

Eun-jeong Park·2023년 7월 15일

javascript

목록 보기
3/6
post-thumbnail
  1. filter()
    -> 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);

결과

["exuberant", "destruction", "present"]
  1. slice()
    -> 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.
const arr = [
  { num: 1, color: "red" },
  { num: 2, color: "black" },
  { num: 3, color: "blue" },
  { num: 4, color: "green" },
  { num: 5, color: "yellow" }
];

console.log(arr.slice(0, 4));

결과

[Object, Object, Object, Object]
0 : Object
  num: 1
  color: "red"
...
이런식으로 나옴
(생략)
  1. concat()
    -> 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.
  • 기존배열을 변경하지 않습니다.
  • 추가된 새로운 배열을 반환합니다.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
console.log(array1.concat(array2));

결과

["a", "b", "c", "d", "e", "f"]
  1. sort()
    -> 원본 배열을 정렬해서 반환해준다.
    문자열을 기준으로 정렬 (기본은 오름차순)

숫자를 sort할 때는 비교함수를 만들어서 넣어줘야한다.

let numbers = [0, 1, 3, 2, 10, 30, 20];

const compare = (a, b) => {  
  if (a > b) {
    // 크다
    return 1;
  }
  if (a < b) {
    // 작다
    return -1;
  }
  // 같다
  return 0;
};

numbers.sort(compare);

console.log(numbers);

결과

[0, 1, 2, 3, 10, 20, 30]

-> 내림차순으로 정렬하려면 compare함수의 return 값을 반대로 바꿔주면 된다.

  1. join()
    -> 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
const arr = ["나는", "야", "멋쟁이", "토마토입니다"];

console.log(arr.join());
console.log(arr.join(" "));
console.log(arr.join("ㅁ"));

결과

나는,야,멋쟁이,토마토입니다
나는 야 멋쟁이 토마토입니다
나는ㅁ야ㅁ멋쟁이ㅁ토마토입니다
profile
지구를 사랑하는 개발자

0개의 댓글