Javascript - Loại bỏ các giá trị null, blank, false, undefined và NaN

Loại bỏ các giá trị null, blank, false, undefined và NaN  trong mảng

Ví dụ:

JavaScript: Remove null, 0, blank, false, undefined and NaN values from an array

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Write a JavaScript function to remove. 'null', '0', '""', 'false', 'undefined' and 'NaN' values from an array.</title>
<script>
function filter_array(test_array) {
    var index = -1,
        arr_length = test_array ? test_array.length : 0,
        resIndex = -1,
        result = [];

    while (++index < arr_length) {
        var value = test_array[index];

        if (value) {
            result[++resIndex] = value;
        }
    }

    return result;
}
document.write(filter_array([NaN, 0, 15, false, -22, '',undefined, 47, null]));
</script>
</head>
<body>
</body>
</html>

Xem ví dụ

Lưu đồ thuật toán:

Flowchart: JavaScript : Remove null, 0, false, undefined and NaN values from an array


Chatbot Tư vấn Lộ trình CNTT 🤖
Chào bạn! Tôi có thể tư vấn về các lộ trình học CNTT dựa trên roadmap.w3typing.com. Hãy chọn một từ khóa dưới đây hoặc gõ câu hỏi của bạn (ví dụ: "Frontend", "Backend", "Python", "DevOps").