Comparing corresponding values of two arrays in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we have two array of numbers of the same length like this −

const arr1 = [23, 67, 12, 87, 33, 56, 89, 34, 25];
const arr2 = [12, 60, 45, 54, 67, 84, 36, 73, 44];

We are required to write a JavaScript function that takes in two such arrays as the first and the second argument. The function should then compare the corresponding values of both the arrays, and the function should return −

  • -1, if the count of corresponding numbers greater in the first array than the second array are more than corresponding numbers greater in the second array

  • 1, if the count of corresponding numbers greater in the second array than the first array are more than the corresponding numbers greater in the first array.

  • 0, if both the counts are equal.

For example −

For the above arrays, the output should be −

const output = 1;

because arr1 has 4 greater corresponding elements while arr2 has 5 greater corresponding elements.

Example

The code for this will be −

 Live Demo

const arr1 = [23, 67, 12, 87, 33, 56, 89, 34, 25];
const arr2 = [12, 60, 45, 54, 67, 84, 36, 73, 44];
const findDominance = (arr1 = [], arr2 = []) => {
   if(arr1.length !== arr2.length){
      return;
   };
   let count = 0;
   for(let i = 0; i < arr1.length; i++){
      const el1 = arr1[i];
      const el2 = arr2[i];
      const diff = el2 - el1;
      console.log(diff)
      count += diff / Math.abs(diff);
   };
   return count / Math.abs(count);
};
console.log(findDominance(arr1, arr2));

Output

And the output in the console will be −

-11
-7
33
-33
34
28
-53
39
19
1
raja
Published on 22-Feb-2021 09:41:02
Advertisements