David David - 5 months ago 10
Javascript Question

Javascript, comparing two arrays in order while skipping non-matching indexes

I have two arrays:

var arr1 = [1,2,3,4,5]
var arr2 = [7,1,8,2,12,3,4,28,5]


I need to go through arr2 looking for matches to arr1, but it has to be in order (1,2,3,4,5). As you can see in arr2, the order does exists, but there are some numbers in between.

[7,1,8,2,12,3,4,28,5]

I have about 50 arrays similar to arr2, so I need to look through each one, and when I find a match, push it out to a "results" object. Small issue though is that some arrays will not have the entire match, may only have 1,2,3 or any variation of the search. Also, if the array I'm searching in is NOT in order, (IE: starts at 2,3,4) skip over it entirely.

The idea is to loop through these arrays, and when I find a match, add a count to the results array.

For example, using arr1 as the search, go through these arrays:

[7,1,8,2,12,3,4,28,5],
[7,1,8,2,12,3,4],
[7,8,1,2],
[1,2,3]

and have a result that looks like this (a dictionary of what was searched for, and a count of what was found) :

{1:4, 2:4, 3:3, 4:2, 5:1}


I tried doing a bunch of for-loops, but I can't figure out how to skip over a number that I'm not looking for, and continue onto the next iteration, while saving the results into a dictionary object.

Answer

Essentially this:

var needle = [1,2,3,4,5]
var collection = [[7,1,8,2,12,3,4,28,5], [7,1,8,2,12,3,4], [7,8,1,2], [1,2,3]]

// start with an object
var results = {}
// populate object with zeros
needle.forEach(i => results[i] = 0)
// define an index to iterate through collection
var i = 0
// define an index to conditionally iterate through "arr1"
var j = 0
// define an index to iterate through collection arrays 
var k = 0
// define surrogate for the arrays in the collection
var arr

while (i < collection.length) {
  
  // get collection array
  arr = collection[i]
  // reset the indices
  j = 0
  k = 0

  while (k < arr.length) {
    // if same element on needle is in a collection array 
    if (needle[j] === arr[k]) {
      // save it in an object starting at 1
      results[needle[j]]++
      j++ // increment needle
    }
    k++ // increment array in collection
  }
  i++ // increment collection
}

console.log(results) // {1:4, 2:4, 3:3, 4:2, 5:1}

I hope that helps!

Comments