So you have two arrays. Search the second array and count how many times each word from the first array occurs in the second one. Display a scrollable list of all the words from the second array and their counts from the first array. I don't want to show only the duplicate values so an intersection function wouldn't help .Use only javascript.
Ex:
listOne = [Pat, cat, hat, Tat, bat, rat];
listTwo = [Pat, mat, sat, rat, cat, Tat, Pat];
And the output would be as follows:
Pat: 2
mat: 0
sat: 0
rat: 1
cat: 1
Tat: 1
I have tried multiple ways and the closest I came up with is this:
function findFreq(listOne, listTwo, concatList) {
var a = [], b = [], lookup = {}, prev;
for(var j = 0; j < listTwo.length; j++) {
lookup[listTwo[j]] = listTwo[j];
}
for (var i = 0; i < concatList.length; i++ ) {
if (concatList[i] !== prev) {
a.push(lookup[concatList[i]]);
b.push(0);
} else {
b[b.length - 1]++;
}
prev = concatList[i];
}
return [a, b];
}
var result = findFreq(listOne, listTwo, concatList);
alert('[' + result[0] + ']<br />[' + result[1] + ']');
As you can see I thought concating the two arrays would be easiest because all of the examples I found of counting the occurrence of elements only dealt with a single array. In fact I took the code from here and tried modifying it to fit my needs.
The problem is the output gives me empty or extra elements.
[Pat,Tat,,cat,,mat,rat,sat]
[2,1,0,1,0,0,1,0]
So the answer is wrong and so is the formatting. I'm probably over complicating this. It is probably easier to compare the two arrays directly, but I just can't figure it out. Any help would be appreciated.
Note: For my program the two arrays I'm using actually come from user specified files that I just use the split() function on. That's why my naming conventions are strange.