0

This is the code i have written to filter out Numeric values from an array, but it is returning the complete array. I am not able to find out the problem in my code. Please help me i am stuck...

<!doctype html>
<html lang="en">
    <head>
  <meta charset="utf-8">
  <title>html demo</title>
</head>
<body>
<script>
    arr = ["apple", 5, "Mango", 6];
    function filterNumeric(arrayName){
        var i = 0;
        var numericArray=[];
        for (i; i <arrayName.length;i++){
            if (typeof(arrayName[i] === 'number')) {
                numericArray+=arrayName[i];
            }
        }
        return numericArray;
    }

    var filter = filterNumeric(arr);
    alert(filter);
</script>

</body>
</html>

2 Answers 2

1

Typo in the typeof check:

if (typeof(arrayName[i]) === 'number') {
//                    ^^^ close the parentheses here
//                                 ^^^ not there
Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript arrays have a built-in filtering method:

var arr = ["apple", 5, "Mango", 6];
var filtered = arr.filter(function(item) { return (typeof item === "number")});
console.log(filtered); // Array [5,6]

As for your original code, beware that typeof is an operator, not a function, so

if (typeof(foo === "whatever")) {
    // ...
}

is equivalent to

if (typeof some_boolean_value) {
    // ...
}

which evaluates to

if ("boolean") {
    // ...
}

which will always be true, this is why you ended up with the whole content with no filtering whatsoever.

Also note that the += operator is not overloaded for arrays, you will end up with a string concatenation of the remaining values:

var foo = [];
var bar = [1,2,3,4];
foo += bar[2];
console.log(foo); // "3"
console.log(typeof foo); // "string"

you must use the push method instead:

var foo = [];
var bar = [1,2,3,4];
foo.push(bar[2]);
console.log(foo); // Array [3]
console.log(typeof foo); // "object"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.