Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of string length in arrays

I've been trying to find the largest difference in length between strings of two different arrays. I put a loop within a loop to iterate and find the difference of all the string lengths.

function mxdiflg(a1, a2) {
  if (a1 === [] || a2 === [])
    return -1;
  var result = 0;
  for (var i in a1) {
    for (var j in a2) {
      var diff = Math.abs(i.length - j.length);
      if (diff > result)
        result = diff;
    }
  }
  return result;
}

However, this code has been ignoring the first if statement that checks for an empty array. It also returns 0 indicating that the loop isn't working.

like image 339
James Avatar asked Dec 21 '25 17:12

James


1 Answers

Firstly, you can't compare arrays in that way. Like Renan said, Arrays are reference types. Change your check to see if there is anything within the array.

if (!a1.length || !a2.length)
  return -1;

Now on the other problem. Looping through an array in a for loop will set your var to be the index you're on.

Either use forEach:

function mxdiflg(a1, a2) {
    ...
    var result = 0;
    a1.forEach(function(i){
       a2.forEach(function(j){
           var diff = Math.abs(i.length - j.length);
           if (diff > result)
               result = diff;
       });
   });
   return result;
}

// mxdiflg(['1','1'], ['111','1'])

or, change your function to get the item from the array, based on index:

function mxdiflg(a1, a2) {
    ...
    var result = 0;
    for (var idx in a1) {
        for (var jdx in a2) {
            var diff = Math.abs(a1[idx].length - a2[jdx].length);
            if (diff > result)
                result = diff;
        }
    }
    return result;
}

// mxdiflg(['1','1'], ['11','1'])

As an aside, if you're using ES6, you could do this. I find it much more readable.

function mxdiflg(a1, a2) {
  if (!a1.length || !a2.length){
    return -1;
  }

  var a1Lengths = a1.map((str) => str.length);
  var a2Lengths = a2.map((str) => str.length);

  var a1MaxLength = Math.max(...a1Lengths);
  var a2MaxLength = Math.max(...a2Lengths);

  return a2MaxLength - a1MaxLength;
}

// mxdiflg(['1','1'], ['111','1']) = 2
like image 67
Dave Salomon Avatar answered Dec 23 '25 08:12

Dave Salomon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!