Search entire array for number of occurrence of index value

Search entire array for number of occurrence of index value
0

#1

I am new to JS and am trying to get a function to take the value of an array (at say index 0) and compare it to another array to find out how many times that value (index 0) is found in the other array, and add that number to a variable (currentCount += 1); then look at the next value (index 1) and do the same thing, etc… until all the index spots are reviewed. I have MOST of the code, but not sure how to loop through the whole comparing array before advancing to next index #. Any help would be appreciated.

PS - I have seen certain examples that use (what I will call) advanced JS, but my understanding is that I am only supposed to use what we have learned so far (1st Semester) - which has not included “reduce”, “.indexOf()”, “every”, “prototype”…etc.

A sample of what I have attempted to do is below (don’t laugh!):

function findZipCodeOccurance() {
	"use strict";
// other variables and Arrays are listed GLOBALLY in main program...
	var currentCount;
        var index;

	currentCount = INITIAL_VALUE;

	for (index = 0; index < uniqueZipCodeArray.length; index += 1) {
        if (uniqueZipCodeArray[index] === duplicateZipCodeArray) {  // <-- not sure what should go here
			currentCount += 1;
			totalOccuranceArray[index] = currentCount + 1;
		}
	}
}

#2

As always some 'pseudo-coding` can be of hands.

These are the ‘steps’ to what you are asking:

1 - look at every element in one array.

for ( i; i < array1.length; i++) // look at array1[i]

2 - look at every element in the second array

for (z; z< array2.length; z++) // look at array2[z]

3 - if the element in the second array is equal to the element in the first array increment a counter:

if (array2[z] === array1[i]) counter++

then it’s just a matter of converting this into an actual working code:

/*
* @param {array} a1  - array that we want to know the values
* @param {array} a2 - array that we want to count in it
* @return - NOTHING: only print in console!
*/
function f(a1, a2) {
  for(var i = 0; i < a1.length; i++) {
    var count = 0;
    for(var z = 0; z < a2.length; z++) {
      if (a2[z] === a1[i]) count++;
    }
   console.log(a1[i] + ' count is ' + count) 
  }
}

This should print in console how many times each element in a1 is inside a2

const arr1 = [1,2,3];
const arr2 = [2,3,3,4,5,1,6,1];

f(arr1, arr2)
// 1 count is 2
// 2 count is 1
// 3 count is 2

This is a very basic and simple implementation, there are shorter and more readable way to do this operations using native array methods like map or reduce.
Plus this doesn’t account for huge number of data :slight_smile:

Hope it helps.


#3

One way to solve this problem would involve a nested for loop (inner and outer). The outer loop would iterate through each character of uniqueZipCodeArray using let’s say index1 and an inner loop would iterate through each character of duplicateZipCodeArray using let’s say index 2 where you would check if ( uniqueZipCodeArray[index1] === duplicateZipCodeArray[index2] ).

To figure out the next part, I ask for clarification about what you want the totalOccuranceArray array contain. Can I assume that each element position (index) in totalOccuranceArray corresponds to the same index for the value in uniqueZipCodeArray? If so, then, before each inner for lop, you can simply assign the value zero to totalOccruanceArray[index1] and inside the true block of the the if statement above, you would only need to increment totalOccuranceArray[index] by one like:

totalOccuranceArray[index]++;

Also, to make this function reusable for other arrays you might want to compare in this same way, you should create 2 parameters (let’s say unique and duplicate) and call your function with uniqueZipCodeArray and duplicateZipCodeArray being passed to the function. Also, I would have the totalOccurancyArray be declared as an empty array local to the function and then have the function return the totalOccurancyArray back as the final step.

If you do not understand how to code the above in the basic JavaScript I have described above, I strongly suggest creating an account at FreeCodeCamp.org and work through the Basic JavaScript and Basic Algorithm sections shown on the map there.


#4

Thank you for taking the time to respond; may I ask (excuse my ignorance): if I use:

if (array2[z] === array1[i]) counter++

doesn’t that only compare array2(say index 4) with array1(index 4), and not the whole array?
what I need is to compare a unique item (zip code) with another array containing many zip codes and count how many times the unique zip code (being tested) is found among the many in the larger array.

Hope the question makes sense, and again, my apologies for the newbeeisms :smirk:


#5

Thanks for your reply Randall…

To clarify, I have an array, ‘uniqueZipCodeArray’; I would like to take each index slot (which holds a zip code) and compare it to a larger array, ‘duplicateZipCodeArray’ to count how many times my unique zip code appears in the larger array. I need to tally each duplicate occurrence for each unique zip code: currentCount and add 1 to account for the unique zip code itself. This currentCount(+1) would be added to: totalOccuranceArray[0] and then begin the next loop for uniqueZipCodeArray[1…] and so on.

The final output will go to a table - column 1 being the contents of uniqueZipCodeArray, with column 2 being the contents of totalOccuranceArray; showing how many time each zip code occurs in both uniqueZipCodeArray and duplicateZipCodeArray.

I believe your suggestion was in-line with this thinking but not sure if you knew why I used certain variables ( though you would probably do this a much simpler way :grin: )

Further replies appreciated.


#6

Being a loop in a loop means that:

for every instance of the first array, go inside the second array and compare those values

So put it in words with those input

const arr1 = [1, 2];
const arr2 = [5, 6];
[+] loop and look at the first value of arr1  ( a1[0] === 1)
   [+] loop inside the second array
       [+] 1 === 5 ? no
       [+] 1 === 6 ? no
   [+] we finished arr2, so the function goes back to the outer loop.

[+] loop and look at the second value of arr1 (a1[1] === 2)
   [+] loop inside the second array
       [+] 2 === 5 ? no
       [+] 2 === 6 ? no
   [+] we finished arr2, so the function goes back to the outer loop.

[+] we finished arr1

This is pretty much how the function will run… hope it’s clear.
If you want to see with your eyes how a loop inside a loop works try running these and look at the output in console:

const fruit = ['mango', 'banana'];
const lang = ['js', 'go', 'perl', 'cpp'];

for(var i = 0; i < fruit.length; i++) {
  for(var z = 0; z < lang.length; z++) {
    console.log('fruit loop is at ' + fruit[i] + ' while lang loop is at ' + lang[z])
  }
}

#7

Thank you, Marmiz, for your GREAT explanation… I had an inkling that the nested loop you showed me would do that, but my brain wasn’t “seeing” it. So thank you very much! :+1::+1::clap: