JavaScript에서 두 객체 배열을 비교하면서 특정 속성(예: amount)을 기준으로 필터링하고 싶다면 map() 메서드와 삼항 연산자(? :)를 함께 활용하면 간단하게 해결할 수 있습니다.
먼저 다음과 같이 두 개의 고객 정보 객체 배열이 있다고 가정해 보겠습니다.
let firstCustomerDetails = [
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails = [
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
];여기서 우리의 목표는 amount 속성 값을 기준으로 두 배열을 비교하여, 더 큰 금액을 가진 객체만 남긴 새로운 배열을 만드는 것입니다.
예제 코드
let firstCustomerDetails = [
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails = [
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
];
var output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key : secondCustomerDetails[position]
);
console.log(output);코드 동작 원리
map()은 첫 번째 배열(firstCustomerDetails)의 각 요소를 순회하며 콜백 함수를 실행합니다. 이때 콜백 함수는 현재 요소(key)와 인덱스(position)를 매개변수로 받습니다.
삼항 연산자가 핵심 역할을 합니다. 첫 번째 배열의 amount 값이 같은 위치에 있는 두 번째 배열의 amount 값보다 크면 첫 번째 배열의 객체를 반환하고, 그렇지 않으면 두 번째 배열의 객체를 반환합니다. 결과적으로 두 배열을 위치별로 비교하여 더 큰 금액을 가진 객체들로 구성된 새로운 배열이 만들어집니다.
실행 방법
위 프로그램을 실행하려면 Node.js 환경에서 다음 명령어를 입력합니다.
node fileName.js
여기서는 파일 이름을 demo83.js로 저장했다고 가정합니다.
출력 결과
프로그램을 실행하면 아래와 같은 결과가 출력됩니다.
PS C:\Users\Amit\JavaScript-code> node demo83.js
[
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 80 }
]결과를 보면 John(400), David(70), Bob(80)처럼 각 위치에서 더 큰 amount 값을 가진 객체들이 선택된 것을 확인할 수 있습니다. 이처럼 map()과 삼항 연산자를 조합하면 별도의 반복문 없이도 간결하고 가독성 좋은 코드로 객체 배열을 필터링할 수 있습니다.