user1943020
user1943020

Reputation:

How can I loop through two arrays comparing values in Javascript?

I have the following Javascript function where the parameters newValue and oldValue are arrays of integers and the same length. Any values in these arrays can be an integer, undefined or null:

function (newValue, oldValue) {


});

Is there some way that I could check the values in the arrays one element at a time and then do an action only if:

newValue[index] is >= 0 and < 999
oldValue[index] is >= 0 and < 999
newValue[index] is not equal to oldValue[index]

What I am not sure of is how can I handle in my checks and ignore the cases where newValue or oldValue are not null and not undefined? I know I can do a check as in if (newValue) but then this will show false when it's a 0.

Update:

I had a few quick answers so far but none are checking the right things which I listed above.

Upvotes: 0

Views: 612

Answers (3)

phylax
phylax

Reputation: 2086

compare against null and undefined:

if (newValue[index] !== null && typeof newValue[index] !== 'undefined') {}

for OPs update:

n = newValue[index];
o = oldValue[index];

if (
  n !== null && typeof n !== 'undefined' && n >= 0 && n < 999 &&
  o !== null && typeof o !== 'undefined' && o >= 0 && o < 999
) {
  // your code
}

for array-elements its not necessary to use typeof so n !== undefined is ok because the variable will exist.

n = newValue[index];
o = oldValue[index];

if (
  n !== null && n !== undefined && n >= 0 && n < 999 &&
  o !== null && o !== undefined && o >= 0 && o < 999 &&
  n !== o
) {
  // your code
}

Upvotes: 1

Easwar Raju
Easwar Raju

Reputation: 273

if (newValue != null || newValue != undefined) && (oldValue != null || oldValue != undefined)

Upvotes: 0

Bergi
Bergi

Reputation: 665584

This will do it:

function isEqual (newValue, oldValue) {
    for (var i=0, l=newValue.length; i<l; i++) {
        if (newValue[i] == null || newValue[i] < 0 || newValue[i] >= 999
         || oldValue[i] == null || oldValue[i] < 0 || oldValue[i] >= 999)
            continue;
        if (newVale[i] !== oldValue[i])
            return false;
    }
    return true;
}

Upvotes: 0

Related Questions