[英]Comparing two arrays in jquery
使用此代碼......
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);
...我能夠找到數組“a”中哪個元素不在數組“b”中。
現在我需要找到:
例如,“隨機數據”在兩個數組中,所以我需要在Array b中返回它的位置,這是零索引。
關於您的評論,這是一個解決方案:
用 jQuery:
$.each( a, function( key, value ) {
var index = $.inArray( value, b );
if( index != -1 ) {
console.log( index );
}
});
沒有 jQuery:
a.forEach( function( value ) {
if( b.indexOf( value ) != -1 ) {
console.log( b.indexOf( value ) );
}
});
您可以迭代a並使用Array.prototype.indexOf
來獲取b中元素的索引,如果indexOf
返回-1
b則不包含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);
});
這應該可行:
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 */
}
所以你的最終數組將是這樣的:
var positions = [[0,2],[1],[3]...]
//implies a[0] == b[0],b[2], a[1] == b[1] and so on.
希望能幫助到你
你可以試試這個:
var a = ['volvo','random data'];
var b = ['random data'];
$.each(a,function(i,val){
var result=$.inArray(val,b);
if(result!=-1)
alert(result);
})
將兩個數組都轉換為字符串並進行比較
if (JSON.stringify(a) == JSON.stringify(b))
{
// your code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.