Home > Web Front-end > JS Tutorial > body text

Compare corresponding values ​​of two arrays in JavaScript

WBOY
Release: 2023-08-26 15:37:05
forward
1389 people have browsed it

在 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];
Copy after login

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 -< /p>

For the above array, the output should be -

const output = 1;
Copy after login

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

Example

This code is -

Live Demonstration< /p>

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));
Copy after login

Output

The output in the console will be -

-11
-7
33
-33
34
28
-53
39
19
1
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template