Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript 배열에서 여러 값으로 요소를 찾는 방법

JavaScript에서 한 배열이 다른 배열의 모든 요소를 포함하고 있는지 확인해야 하는 경우가 종종 있습니다. 이럴 때 every() 메서드와 includes() 메서드를 함께 사용하면 아주 간단하게 해결할 수 있습니다.

핵심 개념 정리

  • Array.prototype.every() — 배열의 모든 요소가 주어진 콜백 함수의 조건을 만족하는지 검사하며, 모두 만족하면 true를 반환합니다.
  • Array.prototype.includes() — 배열에 특정 값이 포함되어 있는지 확인하여 true 또는 false를 반환합니다.

두 메서드를 조합하면 "arr1의 모든 요소가 arr 안에 존재하는가?"라는 질문에 한 줄의 코드로 답할 수 있습니다.

전체 예제 코드

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Find elements of JavaScript array by multiple values</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to see if arr contains all elements of arr1 or not</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let arr = [11, 44, 22, 16, 25, 91, 58];
   let arr1 = [22, 91, 11];
   let contain = arr1.every((item) => arr.includes(item));
   BtnEle.addEventListener("click", () => {
      if (contain) resEle.innerHTML = "The arr contains all elements of arr1";
      else resEle.innerHTML = "The arr doesn't contain all elements of arr1";
   });
</script>
</body>
</html>

코드 동작 원리

위 예제에서 핵심은 다음 한 줄입니다.

let contain = arr1.every((item) => arr.includes(item));

arr1의 각 요소(22, 91, 11)에 대해 arr.includes(item)을 실행하여 해당 값이 arr 배열에 존재하는지 확인합니다. 세 요소가 모두 존재하므로 contain 변수에는 true가 저장됩니다.

실행 결과

위 코드를 브라우저에서 실행하면 다음과 같은 초기 화면이 나타납니다.

JavaScript 배열에서 여러 값으로 요소를 찾는 방법

'CLICK HERE' 버튼을 클릭하면 검사 결과가 화면에 표시됩니다.

JavaScript 배열에서 여러 값으로 요소를 찾는 방법

결과 메시지는 다음과 같습니다.

  • 모든 요소가 포함된 경우: The arr contains all elements of arr1
  • 포함되지 않은 요소가 있는 경우: The arr doesn't contain all elements of arr1

마무리

이처럼 every()includes()를 조합하면 별도의 반복문 없이도 배열 간 포함 관계를 손쉽게 검사할 수 있습니다. ES6 이상 환경이라면 어디서든 사용할 수 있으며, 가독성과 유지보수성 면에서도 뛰어난 패턴이므로 실무에서 적극적으로 활용해 보시기 바랍니다.