4

I have two arrays as below.

bulkSheet[] - Original array
resultsArray[] -  Checking array

I am comparing first element of 'bulkSheet' array with 'resultArray'. Below code is what I have done so far. It executes fine but take long time and gives Exceeded maximum execution time error.

for(var line in bulkSheet) {
  for (var line2 in resultsArray)
  {
    if(bulkSheet[line][0] == resultsArray[line2][0])
    {
      // matched items
    }
  }
}

Is there any fastest way?

iJay
  • 4,205
  • 5
  • 35
  • 63
  • 3
    http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – gurvinder372 Jan 04 '16 at 08:23
  • 1
    Don't use an inner loop. Instead use the `indexOf(value)` method. If the return value from `indexOf()` is -1, then there is no match. If there is a match, it will return the index placement of the match in the array being tested. From the index number you can return that value, or overwrite it if you wish. So, `var isMatched = secondArray.indexOf(value from loop of first array); if (isMatched !== -1) {var matchedValFromArray2 = arrayTwo[isMatched]};` – Alan Wells Jan 05 '16 at 02:54
  • Thank you @sandy-good, you saved my day ! – iJay Jan 05 '16 at 16:20
  • Thank you for letting me know. The question that people referenced as possibly already having the answer, does not show the method I explained. Do you really need to test that both arrays are identical, or do you need to have the code do something if there isn't a match for a particular value? There may be some misunderstanding about the specifics of what you need. Personally, I don't see this question as a duplicate, and voted to reopen. – Alan Wells Jan 05 '16 at 17:44
  • Thanks for the vote to reopen. I wanted to identify if there isn't a match for a particular value. your method made it faster. I didn't aware about indexOf() method. Thanks again,cheers! – iJay Jan 06 '16 at 05:48

1 Answers1

4

Thank you @sandy-good !, If it is an 1D array we can use indexOf() method.

for(var line in firstArray) 
{
 var isMatched = secondArray.indexOf(firstArray[line]); 
 if (isMatched !== -1) 
 {
   var matchedValFromArray2 = secondArray[isMatched]
 };
}

If you want to compare 2D array (or two rows of a spreadsheet), you can use .join() method.

for(var i in firstArray)
{
  var duplicate = false;
  for(var j in secondArray)
  {
    if(firstArray[i].join() == secondArray[j].join())
    {
      var matchedValFromArray2 = firstArray[i];
      break;
    }
   }
 } 
iJay
  • 4,205
  • 5
  • 35
  • 63