Thread: filter() function question View Single Post
01-04-2013, 11:16 PM   PM User | #4
Old Pedant
Supreme Master coder!

Join Date: Feb 2009
Posts: 24,938
Thanks: 75
Thanked 4,305 Times in 4,272 Posts
Quote:
 Originally Posted by DaveyErwin function addOne(element, index, array) { return ++array[index]; } var Aarr = [0,1,2,3,4,5,6,7,8,9]; Aarr.filter(addOne); alert(Aarr);
Well, yes. That will increment each element of the array by one.

But you would get the same results using
Code:
```function addOne(element, index, array)
{
++array[index];
return false; // or return Math.random() < 0.5; even
}```
The return value from filter has no impact on what happens in the *original* array.

If you were to do this:
Code:
```function addOne(element, index, array) { return ++array[index]; }
var Aarr = [0,1,2,3,4,5,6,7,8,9];
You would find that Barr will contain a copy of the *original* array (0 through 9) while Aaar has every element incremented by one.

But, again, if you started with (say)
Code:
`var Aarr = [0,1,-1,3,-1,7,0];`
Then you would end up with
Code:
```Aarr == [ 1,2,0,4,0,8,1 ]
Barr == [ 0,1,3,7,0 ]```
Because the -1s on being increment become zero and so the return from filter is, effectively, false and those -1s get filtered out.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.