Home >Web Front-end >JS Tutorial >Compare corresponding values ​​of two arrays in JavaScript

Compare corresponding values ​​of two arrays in JavaScript

WBOY
WBOYforward
2023-08-26 15:37:051424browse

在 JavaScript 中比较两个数组的对应值

Suppose we have two arrays of numbers with the same length as shown below -

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

We need to write a JavaScript function that accepts two such arrays as The first and second parameters. The function should then compare the corresponding values ​​of the two arrays and if the count of the corresponding number in the first array is greater, the function should return -

  • -1

  • 1. If the number of corresponding numbers in the second array that is larger than the first array is greater than the number of corresponding numbers in the second array

  • 1The corresponding number in the first array is larger.

  • If the two counts are equal, it is 0.

For example -

For the above array, the output should be -

const output = 1;

because arr1 has 4 larger corresponding elements and arr2 has 5 larger corresponding elements.

Example

This code is -

Live Demonstration

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

The output in the console will be -

-11
-7
33
-33
34
28
-53
39
19
1

The above is the detailed content of Compare corresponding values ​​of two arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete