상세 컨텐츠

본문 제목

배열 메서드 변형

Javascript

by loeybho 2024. 3. 24. 11:03

본문

5가지의 배열 변형 메서드 🪄

 

1. filter

기존 배열에서 조건을 만족하는 요소들만 필터링 하여 새로운 배열로 반환

let arr1 = [
  { name: "이정환", hobby: "테니스" },
  { name: "이정환", hobby: "테니스" },
  { name: "이정환", hobby: "테니스" },
];

const tennisPeople = arr1.filter((item) =>
item.hobby === "테니스");

console.log(tennisPeople);

 

2. map

배열의 모든 요소를 순회하면서, 각각 콜백함수를 실행하고, 그 결과값을 모아서 새로운 배열 반환

let arr2 = [1, 2, 3];
const mapResult1 = arr2.map((item, index, array) => {
  // console.log(index, item);
  return item * 2;
});

console.log(mapResult1); // [2,3,4]

 

3. sort

배열을 사전순으로 정렬하는 메서드

let arr3 = ["b", "a", "c"];
arr3.sort();

console.log(arr3); // ["a","b","c"]

//오름차순으로 정렬
let arr3 = [10, 3, 5];
arr3.sort((a, b) => {
  if (a > b) {
    //b가 a 앞에 와라
    return 1; // -> b,a 배치
  } else if (a < b) {
    return -1; //-> a,b 배치
  } else {
    // 두 값의 자리를 바꾸지 마라
    return 0; // a,b 자리를 그대로 유지
  }
});

console.log(arr3); // [10,5,3]

 

4. toSorted (가장 최근에 추가된 최신 함수)

sort()와 유사하지만, 정렬된 새로운 배열을 반환하는 메서드

let arr5 = ["c", "a", "b"];
const sorted = arr5.toSorted();

console.log(arr5); // ["c", "a", "b"]
console.log(sorted); // ["a", "b", "c"]

 

5. join

배열의 모든 요소를 하나의 문자열로 합쳐서 변환하는 메서드

let arr6 = ["hi", "im", "winterlood"];
const joined = arr6.join(" ");
console.log(joined); // hi im winterlood

 

 참고 자료 🔖

https://reactjs.winterlood.com/fc0a951e-41cd-4cc5-8f47-7507965bbe41#8f2d70d5e8334377bb56f0a3f9101de2

'Javascript' 카테고리의 다른 글

자바스크립트의 기초 (데이터 타입과 함수)  (0) 2024.06.11
DOM  (0) 2024.05.07
배열 메서드 순회와 탐색  (0) 2024.03.24
배열 메서드 요소 조작  (0) 2024.03.24
async/await  (0) 2024.02.20

관련글 더보기