Maximum absolute difference of the length of strings from two arrays in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in two arrays, a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.

Our function should find the value of −

max(abs(length(x) − length(y)))

Example

Following is the code −

 Live Demo

const arr1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
const arr2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"];
const findMaxAbsDiff = (arr1 = [], arr2 = []) => {
   if(arr1.length === 0 || arr2.length === 0){
      return -1;
   };
   let l1 = arr1.map(str => str.length)
   let l2 = arr2.map(str => str.length)
   return Math
   .max(Math.max(...l1) - Math.min(...l2), Math.max(...l2) - Math.min(...l1));
};
console.log(findMaxAbsDiff(arr1, arr2));

Output

13
raja
Published on 20-Apr-2021 13:03:16
Advertisements