JS - 배열메소드

seungbox·2023년 2월 18일

JS

목록 보기
1/2

본문은 아래 링크를 참조하여 읽고 각색한 글입니다.

13 Useful JavaScript Array Tips and Tricks You Should Know

  • 배열은 프로그래밍 기초단계에서 배우는 가장 기본적인 주제

1. 배열에서 중복제거(splice)

let fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
let uniqueFruits = Array.from(new Set(fruits));
   console.log(uniqueFruits); // [“banana”, “apple”, “orange”, “watermelon”, “grape”]
let uniqueFruits2 = [new Set(fruits)];
   console.log(uniqueFruits2); // [“banana”, “apple”, “orange”, “watermelon”, “grape”]
  • new Set()을 사용하고
    Array.from / ...(스프레드 연산자) 를 사용하여 중복 제거를 할 수 있다.

2. 배열에서 특정 값 바꾸기(new Set(Array.from, 스프레드 연산자))

let fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”];
fruits.splice(0, 2, “potato”, “tomato”);
  console.log(fruits); // [“potato”, “tomato”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]
  • splice()를 사용하여 수정 시작위치, 변경하려는 값의 수, 새로운 값을 지정할 수 있다.
    ※ splice 메소드는 원본 배열을 변경한다.

3. map없이 배열 매핑(Array.from)

let friends = [
    { name: ‘John’, age: 22 },
    { name: ‘Peter’, age: 23 },
    { name: ‘Mark’, age: 24 },
    { name: ‘Maria’, age: 22 },
    { name: ‘Monica’, age: 21 },
    { name: ‘Martha’, age: 19 },
]
let friendsNames = Array.from(friends, ({name}) => name);
  console.log(friendsNames); // [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]
  • Array.from은 map과 유사한 효과를 주고 매우 깨끗한 코드를 얻을 수 있다.
    ※ 하지만 Array.from 과 map은 효율 면에서 map이 더 빠르기 때문에 둘다 쓸수 있는 상황이면 map을 쓰는것이 좋다.

4. 배열 비우기(배열길이를 0으로 변경)

let fruits = [“banana”, “apple”, “orange”, “watermelon”, “apple”, “orange”, “grape”, “apple”]
fruits.length = 0;
  console.log(fruits); // []
  • 배열을 비우려면 다음을 수행해야 한다. 배열의 길이를 0으로 설정

5. 배열을 객체로 변환(스프레드 연산자(...))

let fruits = [“banana”, “apple”, “orange”, “watermelon”];
let fruitsObj = { …fruits };
  console.log(fruitsObj);
// {0: “banana”, 1: “apple”, 2: “orange”, 3: “watermelon”, 4: “apple”, 5: “orange”, 6: “grape”, 7: “apple”}
  • 스프레드 연산자 (...)를 사용

6. 데이터로 배열 채우기(fill)

let newArray = new Array(10).fill(1);
  console.log(newArray); //  [“1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”, “1”]
  • 일부 데이터로 채우고 싶거나 동일한 값을 가진 배열이 필요할때 fill 사용

7. 어레이 병합(스프레드 연산자(...))

let fruits = [“apple”, “banana”, “orange”];
let meat = [“poultry”, “beef”, “fish”];
let vegetables = [“potato”, “tomato”, “cucumber”];
let food = […fruits, …meat, …vegetables];
  console.log(food);
// [“apple”, “banana”, “orange”, “poultry”, “beef”, “fish”, “potato”, “tomato”, “cucumber”]
  • concat 메소드 대신 스프레드 연산자 사용
    ※ 모던자바스크립트 Deep dive에 따르면 push/unshift , concat 대신에 ES6의 스프레드문법을 일관성 있게 사용하는 것을 권장한다고 한다.

8. 두 배열의 공통 요소 찾기(filter, includes)

let arr1 = [0, 2, 4, 6, 8, 8];
let arr2 = [1, 2, 3, 4, 5, 6];
let newArray =[new Set(arr1)].filter(item => arr2.includes(item)));
  console.log(newArray) // [2, 4, 6]
  • arr2에 includes 함수를 통해서 arr1의 값(x)이 있으면 false, 아니면 true를 반환하여
    arr1의 filter 함수를 통해 true 값만 걸러내 새로운 배열을 만든다.

9. 배열에서 잘못된 값 제거(filter())

let mixedArr = [0, “blue”, “”, NaN, 9, true, undefined, “white”, false];
let trueArr = mixedArr.filter(Boolean);
  console.log(trueArr); //  [“blue”, 9, true, “white”]
  • JS에서 거짓 값은 (false, 0, "", null, NaN, undefined)이다.
    배열에서 거짓 값 제거는 filter()를 사용할 수 있다.

10. 배열에서 임의의 값 가져오기

let colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
let randomColor = colors[(Math.floor(Math.random() * (colors.length)))]
 //
  • 배열에서 무작위로 값을 선택할 때 배열의 길이에 따라 임의의 인덱스 번호를 얻을 수 있다.
    Math.random()로 0보단 크고 1보다 난수를 지정한 후 배열의 길이만큼 곱하고
    Math.floor()를 이용해 소수점을 버린다.

11. 배열 뒤집기

let colors = [“blue”, “white”, “green”, “navy”, “pink”, “purple”, “orange”, “yellow”, “black”, “brown”];
let reversedColors = colors.reverse();
  console.log(reversedColors); 
// [“brown”, “black”, “yellow”, “orange”, “purple”, “pink”, “navy”, “green”, “white”, “blue”]
  • reverse를 사용하여 배열을 뒤집을 수 있다.

12. .lastIndexOf() 메서드

let nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
let lastIndex = nums.lastIndexOf(5);
  console.log(lastIndex); // returns 9
  • 배열에 중복된 값이 있으면 lastIndexOf()로마지막으로 발생한 위치를 찾을 수 있다.

13. 배열의 모든 값 합계

let nums = [1, 5, 2, 6];
let sum = nums.reduce((x, y) => x + y);
console.log(sum); // returns 14
  • reduce 메소드를 배열의 합을 구할 수 있다.

※ 그러나 reduce는 배열의 합만을 구하는 메소드는 아니고 다양한 기능을 구현 할 수 있으므로
reduce에 대해서 다시 공부를 하여 정리를 하려고 한다.

profile
함께 하는 개발자

0개의 댓글