자바스크립트 배열에서 null 값을 걸러내고 null이 아닌 값만 남기고 싶다면 filter() 메서드를 사용하는 것이 가장 간단한 방법입니다. filter()는 배열의 각 요소에 대해 콜백 함수를 실행하고, 그 결과가 참(truthy)으로 평가되는 요소들만 모아 새로운 배열을 반환합니다.
예제 코드
var names = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", "Adam", null, null];
console.log("null 제거 전 =");
console.log(names);
var filterNullValues = names.filter(obj => obj);
console.log("null 값 필터링 후 =");
console.log(filterNullValues);여기서 콜백 함수 obj => obj는 각 요소 자신을 조건으로 사용합니다. 자바스크립트에서 null, undefined, 빈 문자열("")은 모두 거짓(falsy) 값으로 평가되기 때문에, 이 방식 하나로 null뿐 아니라 undefined와 빈 문자열까지 한 번에 제거할 수 있습니다.
반대로 null 값만 정확히 제거하고 나머지 falsy 값은 유지하고 싶다면 다음과 같이 비교 연산자를 명시적으로 사용하면 됩니다.
var onlyNullRemoved = names.filter(obj => obj !== null);
프로그램 실행 방법
위 프로그램을 실행하려면 Node.js 환경에서 다음 명령어를 입력합니다.
node fileName.js
실행 결과
파일 이름이 demo148.js인 경우, 위 코드를 실행했을 때 출력되는 결과는 다음과 같습니다.
PS C:\Users\Amit\JavaScript-code> node demo148.js Before filter null=[ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ] After filtering the null values= [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
실행 결과를 보면 원래 배열에 포함되어 있던 null, undefined, 빈 문자열이 모두 제거되고, 'John', 'David', 'Mike', 'Bob', 'Adam'처럼 실제 의미 있는 값만 남은 것을 확인할 수 있습니다.