admin管理员组文章数量:1405603
Im stuck on a piece of javascript for the last 4 hours!
The question is how do I count similarities between 2 arrays like so:
arrayA = [a,b,c,d,e,f,g];
arrayB = [c,d,e];
The answer shoud be three. The only piece of code I have at the moment produces a infinite loop :(
Pleas help
Im stuck on a piece of javascript for the last 4 hours!
The question is how do I count similarities between 2 arrays like so:
arrayA = [a,b,c,d,e,f,g];
arrayB = [c,d,e];
The answer shoud be three. The only piece of code I have at the moment produces a infinite loop :(
Pleas help
Share Improve this question edited Nov 13, 2013 at 8:39 geevee 5,4615 gold badges32 silver badges50 bronze badges asked Nov 13, 2013 at 8:23 Bart KlasterBart Klaster 533 silver badges11 bronze badges 1- Perhaps you could show the code that produces the infinite loop? – lonesomeday Commented Nov 13, 2013 at 8:27
4 Answers
Reset to default 5One way would be to filter arrayA
by checking each to see if it's in arrayB
, then getting the length
of the new array:
arrayA.filter(function(el) {
return arrayB.indexOf(el) >= 0;
}).length;
This uses:
Array#indexOf
Array#filter
Array#length
NB that the first two are not available in old browsers, so need to be shimmed using the code in the links given.
here you go (cross browser solution):
[note that .filter()
method wont work in IE8 and other old browsers, so i suggest the following approach]
1) define the function:
function count_similarities(arrayA, arrayB) {
var matches = 0;
for (i=0;i<arrayA.length;i++) {
if (arrayB.indexOf(arrayA[i]) != -1)
matches++;
}
return matches;
}
2) call it:
var similarities = count_similarities(arrayA, arrayB);
alert(similarities + ' matches found');
if you don't bother about old browsers support, i'd highly suggest lonesomeday's answer.
hope that helps.
You should take each element of one array and check if it is present in the other using arrayA.indexOf(arrayB[i]) If it doesnt return -1 then increment a count variable. At the end count is your answer.
You can go with $.inArray() function to do this
http://api.jquery./jQuery.inArray/
$(function () {
arrayA = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
arrayB = ['c', 'd', 'e'];
var matchCount = 0;
$.each(arrayB, function (index, value) {
if ($.inArray(value, arrayA) != -1)
matchCount++;
});
alert("Matched elements : " + matchCount);
});
本文标签: count similarities between two arrays with javascriptStack Overflow
版权声明:本文标题:count similarities between two arrays with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744328437a2600841.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论