3

I have an array of arbitrary elements and need to get only number elements. I tried arr.filter((c) => !isNaN(parseInt(arr[c]))); but that didn't work. I still have a full array. What is wrong here and what else can I do?

2
  • 2
    c is the value arr[c] is not defined. Commented Oct 28, 2018 at 21:20
  • What do you mean by “number elements”? That parseInt check is going to include strings that only start with digits. If the array elements are JavaScript numbers, you just need typeof; if you want to check for strings of a particular format, I’d recommend a regular expression. Commented Oct 28, 2018 at 21:21

2 Answers 2

7

The first argument in the callback to .filter is the array item being iterated over - if c is the array item, then referencing arr[c] usually doesn't make much sense. Try using a simple typeof check instead:

const arr = [3, 'foo', { bar: 'baz' }, false, 4, 5];
console.log(arr.filter(item => typeof item === 'number'));

Sign up to request clarification or add additional context in comments.

Comments

1

You're trying to access an index using the numbers, change to this:

let newArray = arr.filter((c) => !isNaN(parseInt(c)));
                                                 ^

Further, you need to use the array which is returned by the function filter.

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.