views:

29

answers:

1

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 mapped version returns the correct result. However the filtered 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>
+2  A: 

No, the filter method doesn't return the unfiletered array. It returns an array containing the items where the inner function returns true.

As you are not returning a boolean value from the inner function, the value is converted to boolean, so the object reference is converted to true. Thus, it returns a new array that contains all the items from the original array.

The filter method doesn't do the same as the map method. The map method is used to convert each item of an array, while the filter method is used to select certain items of an array. Comparing the performance between the methods is moot, as only one of them does what you want to do.

Guffa
Ahh. It appears I misunderstood how the filter functon works. I was under the impression that it returned a modified object to an array.
graham.reeds