Reputation:
In JavaScript I have a JSON array like this:
var r = [{"name":"a","bool":false},{"name":"b","bool":false},
{"name":"c","bool":false},{"name":"a","bool":false},
{"name":"b","bool":false},{"name":"c","bool":true},
{"name":"a","bool":true}];
I want to build another array containing all the objects where name=="a" and bool==false. I solved this by looping, but I wanted to know if there is another way to do it.
How can I do?
[edit] My loop was:
var rLen = r.length;
var newArray = [];
for(var i=0;i<rLen;i++) {
if(r[i].name=="a"&&r[i].bool==false) {
newArray.push(r[i]);
}
}
Upvotes: 1
Views: 50
Reputation: 35194
In the end it will always be solved by loops internally, e.g.
var r = [{"name":"a","bool":false},{"name":"b","bool":false},
{"name":"c","bool":false},{"name":"a","bool":false},
{"name":"b","bool":false},{"name":"c","bool":true},
{"name":"a","bool":true}];
var result = r.filter(function(item){
return item.name === 'a' && !item.bool;
});
If you look at the polyfill, you'll notice the loop:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) { // <--
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
Since you're interested in performance, here is a jsperf comparing the two: http://jsperf.com/aarontgrogg-array-filter-vs-for-loop
Upvotes: 4
Reputation: 7641
may be
var r1 = r.filter(function(item){ return item.name === "a" && !item.bool; });
Upvotes: 1