As a continuation of my min/max across an array of objects I was wondering about the performance comparisons of filter vs map.
So I put together a test on the values in my code as was going to look at the results in FireBug.
This is the code:
var _vec = this.vec;
min_x = Math.min.apply(Math, _vec.filter(function(el){ return el["x"]; }));
min_y = Math.min.apply(Math, _vec.map(function(el){ return el["x"]; }));
The map
ped version returns the correct result. However the filter
ed version returns NaN. Breaking it out, stepping through and finally inspecting the results, it would appear that the inner function returns the x
property of _vec
but the actual array returned from filter
is the unfiltered _vec
.
I believe my usage of filter
is correct - can anyone else see my problem?
Here's a simple test:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>S:GTC Map Test</title>
</head>
<body>
<script type="text/javascript">
function vector(x,y,z) { this.x = x; this.y =y; this.z=z; }
var vec = [];
vec.push(new vector(1,1,1));
vec.push(new vector(2,2,2));
vec.push(new vector(2,3,3));
var _vec = vec;
min_x = Math.min.apply(Math, _vec.filter(function(el){ return el["x"]; }));
min_y = Math.min.apply(Math, _vec.map(function(el){ return el["x"]; }));
document.write("<br>filter = " + min_x);
document.write("<br>map = " + min_y);
</script>
</body>
</html>