0

I've found something interesting and I don't know why it's happening.

If I try in google chrome developer tools, the following two staments

(Array([1,2,3])).filter(function (item, index, array) {
    return item === 1;
}); ==> []

and

([1,2,3]).filter(function (item, index, array) {
     return item === 1;
}); ==> [1]

The results are an empty array for the first statement and array with a single value (1) for the second

Inspecting the parameters for the callback function, i found that in the first statement the arguments are (array, index, value) and for the second statemente are(value, index, array).

Inspecting with typeof and constructor of both objects the result are the expected, and the same "object", and Array.

Why is this happening?

Thanks

1
  • Thanks to all for your ansewrs, most of them are correct, after your answers I found the issue wich i didn't asked because i thought it was not related. I was using typescript, but i forget that casting in typescript is written with <> not with (). That's why my code got transpiled in the first statement, wich is obviously is not correct. Commented Jul 27, 2016 at 16:30

4 Answers 4

5

Because that's not how you define an array with Array().

Should be without the square brackets, otherwise it's an array of a single element, which is also an array ([1,2,3]).

Array(1,2,3)

That inner array never equals to 1 (basically you check [1,2,3] == 1), so the result is an empty array.

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

Comments

1

If you define an array by using Array([1,2,3]) this code, then the following array will be created,

[[1,2,3]]

Since you are pushing an array into another one. And if you really want the Array function to create an array by reading an array then you have to write something like this,

Array.apply([], [1,2,3])

But the above one is completely pointless. Again I am telling it is completely pointless since we are having an array that we require in our hand. But just for a knowledge you can know about it.

Comments

0

Array([1,2,3]) create array of arrays [[1, 2, 3]] so .map()function will iterate one time only.

If you want to create array with Array constructor use next syntax:

Array(1,2,3) 

Comments

0

the shorter is the better :

[1,2,3].filter(item => item === 1);

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.