w3resource

JavaScript: Check whether there is at least one element which occurs in two given sorted arrays of integers

JavaScript Basic: Exercise-100 with Solution

Write a JavaScript program to check if there is at least one element in two given sorted arrays of integers.

Visual Presentation:

JavaScript: Check whether there is at least one element which occurs in two given sorted arrays of integers.

Sample Solution:

JavaScript Code:

// Function to check if there's a common element in two arrays
function check_common_element(arra1, arra2) {
  for (var i = 0; i < arra1.length; i++) {
    // Check if the current element from arra1 exists in arra2
    if (arra2.indexOf(arra1[i]) != -1) {
      return true; // If found, return true
    }
  }
  return false; // If no common element is found, return false
}

// Example usage
console.log(check_common_element([1, 2, 3], [3, 4, 5])); // Should return true as 3 is a common element
console.log(check_common_element([1, 2, 3], [5, 6, 7])); // Should return false as no common elements are found   

Output:

true
false

Live Demo:

See the Pen javascript-basic-exercise-100 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Check whether there is at least one element which occurs in two given sorted arrays of integers

ES6 Version:

// Function to check if two arrays have any common elements
const check_common_element = (arra1, arra2) => {
  for (let i = 0; i < arra1.length; i++) {
    if (arra2.indexOf(arra1[i]) !== -1) {
      return true; // If a common element is found, return true
    }
  }
  return false; // Return false if no common elements found
}

console.log(check_common_element([1, 2, 3], [3, 4, 5])); // Example usage
console.log(check_common_element([1, 2, 3], [5, 6, 7])); // Example usage

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to check whether it is possible to rearrange characters of a given string in such way that it will become equal to another given string.
Next: JavaScript program to check whether a given string contains only Latin letters and no two uppercase and no two lowercase letters are in adjacent positions.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.