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?

5
  • 3
    stackoverflow.com/questions/7837456/… Commented Jan 4, 2016 at 8: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]}; Commented Jan 5, 2016 at 2:54
  • Thank you @sandy-good, you saved my day ! Commented Jan 5, 2016 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. Commented Jan 5, 2016 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! Commented Jan 6, 2016 at 5:48

1 Answer 1

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;
    }
   }
 } 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.