What is the shorthand and best way to find intersection?
f = ["A","B","C","D","E","F"]; //might be less than 8
b = [1,0,0,1,0,0,0,0]; //always 8 elements
Desired resulting array ["A","D"]
You could use Array#filter
var f = ["A", "B", "C", "D", "E", "F"],
b = [1, 0, 0, 1, 0, 0, 0, 0],
r = f.filter((_, i) => b[i]);
console.log(r);
Assuming your f array is never longer than your b array
f.filter((item, index) => b[index] === 1);
If you're wanting this completely shorthand you can rename item and index and drop the === 1:
f.filter((a, i) => b[i]);
var f = ["A","B","C","D","E","F"]; //might be less than 8
var b = [1,0,0,1,0,0,0,0]; //always 8 elements
console.log(f.filter((a, i) => b[i]));
var f = ["A","B","C","D","E","F"];
var b = [1,0,0,1,0,0,0,0];
var res = f.filter(function(e, i) {
return b[i]; // short for return b[i] === 1;
});
console.log(res);
Or even shorter using arrow functions like this:
var f = ["A","B","C","D","E","F"];
var b = [1,0,0,1,0,0,0,0];
var res = f.filter((e, i) => b[i]);
console.log(res);
[A,C].[A, C]. The OP should have presented the proper conditionsAnother Way :
$(function(){
f = ["A","B","C","D","E","F"];
b = [1,0,0,1,0,0,0,0];
x = [];
$.each(b,function(key, value){
value?x.push(f[key]):'';
});
console.log(x)
});
Since for loops are faster than filter method i suggest this:
var results = [];
for(var i=0;i<b.length;i++){
if (b[i]) results.push(f[i]);
}
== 1 with truthy values.
"C", at it's the third element inf? shouldn't beD?