Reputation: 837
Using this code...
var a = ['volvo','random data'];
var b = ['random data'];
var unique = $.grep(a, function(element) {
return $.inArray(element, b) == -1;
});
var result = unique ;
alert(result);
...I am able to find which element of Array "a" is not in Array "b".
Now I need to find:
For example "Random data" is in both arrays, so I need to return its position in Array b which is zero index.
Upvotes: 3
Views: 42155
Reputation: 1678
Convert both array to string and compare
if (JSON.stringify(a) == JSON.stringify(b))
{
// your code here
}
Upvotes: 6
Reputation: 1050
Regarding your comment, here is a solution:
with jQuery:
$.each( a, function( key, value ) {
var index = $.inArray( value, b );
if( index != -1 ) {
console.log( index );
}
});
without jQuery:
a.forEach( function( value ) {
if( b.indexOf( value ) != -1 ) {
console.log( b.indexOf( value ) );
}
});
Upvotes: 6
Reputation: 389
You can try this:
var a = ['volvo','random data'];
var b = ['random data'];
$.each(a,function(i,val){
var result=$.inArray(val,b);
if(result!=-1)
alert(result);
})
Upvotes: 1
Reputation: 4847
This should probably work:
var positions = [];
for(var i=0;i<a.length;i++){
var result = [];
for(var j=0;j<b.length;j++){
if(a[i] == b[j])
result.push(i);
/*result array will have all the positions where a[i] is
found in array b */
}
positions.push(result);
/*For every i I update the required array into the final positions
as I need this check for every element */
}
So your final array would be something like:
var positions = [[0,2],[1],[3]...]
//implies a[0] == b[0],b[2], a[1] == b[1] and so on.
Hope it helps
Upvotes: 1
Reputation: 4841
You could just iterate over a and use Array.prototype.indexOf
to get the index of the element in b, if indexOf
returns -1
b does not contain the element of a.
var a = [...], b = [...]
a.forEach(function(el) {
if(b.indexOf(el) > 0) console.log(b.indexOf(el));
else console.log("b does not contain " + el);
});
Upvotes: 1