TypedArray의 filter() 함수는 콜백 함수를 인수로 받아, 타입 배열(typed array)의 모든 요소가 해당 함수로 구현된 조건 테스트를 통과하는지 검사하고, 테스트를 통과한 요소들만으로 구성된 새로운 배열을 생성합니다. 원본 배열은 변경되지 않습니다.
문법(Syntax)
filter() 함수의 기본 문법은 다음과 같습니다.
typedArray.filter(function_name)
콜백 함수의 매개변수
- element: 현재 처리 중인 배열의 요소
- index: 현재 처리 중인 요소의 인덱스
- array: filter()를 호출한 원본 타입 배열
콜백 함수는 각 요소에 대해 true 또는 false를 반환해야 하며, true를 반환한 요소만 새 배열에 포함됩니다. 조건을 만족하는 요소가 하나도 없으면 빈 배열이 반환됩니다.
예제(Example)
다음 예제에서는 Int32Array에 filter() 함수를 적용하여 35보다 큰 값들만 추출합니다.
<html>
<head>
<title>JavaScript TypedArray filter Method</title>
</head>
<body>
<script type="text/javascript">
var int32View = new Int32Array([64, 89, 65, 21, 14, 66, 87, 55]);
document.write("Contents of the typed array: " + int32View);
document.write("<br>");
function testResult(element, index, array) {
var ele = element > 35;
return ele;
}
result = int32View.filter(testResult);
document.write("Elements that are greater than 35: " + result);
</script>
</body>
</html>
실행 결과(Output)
Contents of the typed array: 64,89,65,21,14,66,87,55 Elements that are greater than 35: 64,89,65,66,87,55
핵심 포인트
- filter()는 조건을 만족하는 요소들만 담은 새로운 타입 배열을 반환합니다.
- 원본 배열(int32View)은 전혀 변경되지 않습니다.
- 위 예제에서는 testResult 함수가 각 요소가 35보다 큰지 검사하여, 해당 조건을 통과한 64, 89, 65, 66, 87, 55만 결과 배열에 포함되었습니다.
- 일반 Array의 filter() 메서드와 동작 방식이 동일하며, 타입 배열에서도 동일하게 활용할 수 있습니다.