I want to compare with array 1 with array 2, array 1 has array of objects. whatever items available in array 2 those should be also available on array 1. If so, then, i have to push the item from array 2 to new array, then, i return newly created finalArray. I did the code and it is working fine as i mentioned, But, this below code executes the 'for loop' many items that i don't want.
I wanted to avoid many loop execution.
var arr1 = [{"count":1,"name":"hitler"},{"count":1,"name":"cool"},{"count":1,"name":"cooola"},{"count":1,"name":"cute"},{"count":1,"name":"nyle"},{"count":1,"name":""},{"count":1,"name":"path"},{"count":1,"name":"root"},{"count":1,"name":"sssstag"},{"count":1,"name":"ssssu tag"},{"count":1,"name":"sutag"},{"count":1,"name":"tag2"},{"count":1,"name":"arrogant"},{"count":1,"name":"test01"},{"count":1,"name":"test10"},{"count":1,"name":"uber"},{"count":1,"name":"union"},{"count":1,"name":"assettag"},{"count":1,"name":"wire"}];
function intersect_arrays(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i].name === b[e] ) matches.push( b[e] );
}
}
return matches;
}
var arr2 = ["hilter","arrogant","cool","uber"];
var finalArray = intersect_arrays(arr1, arr2);
console.log(finalArray);
Anybody help me with better way to achieve the same?
b, you need to look at up to every element ina. Some of the answers you've received are more readable using higher order functions, but they're performing the same number of operations, I believe.