NOTE: I'm bringing this question up in code review rather than stack overflow since I already have a working solution. I just am looking for ways to do it better.
I have two arrays. One is an array of simple strings (i.e. A1
), while the other is an array of objects (i.e. A2
). I need to pluck only those objects from A2
, that have relevant keys present in A1
.
Here is my implementation using a double for
loop. It works, but is not elegant or efficient, I feel. How do I make this run better? Use of ext libraries such as underscore JS is allowed.
var A1 = ["1","2","3","4"];
var A2 = [
{label:"one", value:"1"},
{label:"two", value:"2"},
{label:"three", value:"3"},
{label:"four", value:"4"},
{label:"five", value:"5"},
{label:"six", value:"6"},
];
var result = [];
for(var i=0; i<A2.length; i++){
for(var j=0; j<A1.length; j++ ){
if(A1[i] == A2[j].value){
result.push( A2[j]);
}
}
}
The output of the above is :
result = [
{label:"one", value:"1"},
{label:"two", value:"2"},
{label:"three", value:"3"},
{label:"four", value:"4"},
]