To find similar values from two different arrays in JavaScript, you can use a loop and conditional statements to compare each element of the first array with the elements of the second array. If a match is found, you can add that value to a new array.

Here's an example code:

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [3, 5, 7, 9];

let similarValues = [];

for (let i = 0; i < arr1.length; i++) {
  for (let j = 0; j < arr2.length; j++) {
    if (arr1[i] === arr2[j]) {
      similarValues.push(arr1[i]);
    }
  }
}

console.log(similarValues); // Output: [3, 5]

In this example, we have two arrays 'arr1' and 'arr2'. We define a new empty array 'similarValues' to store the similar values. We use two nested loops to iterate through each element of both arrays and compare them. If a match is found, we push that value to the 'similarValues' array.

Finally, we log the 'similarValues' array to the console, which gives us the output '[3, 5]'.

Find Common Elements in Two Arrays: JavaScript Example

原文地址: https://www.cveoy.top/t/topic/oX4e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录