JavaScript: Test whether an array of integers of length 2 contains 1 or a 3
JavaScript Basic: Exercise-77 with Solution
Check if Array Contains 1 or 3
Write a JavaScript program to test whether an array of integers of length 2 contains 1 or 3.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function checks if the array 'nums' contains either 1 or 3
function contains13(nums) {
// Check if 1 is present at any index or 3 is present at any index
if (nums.indexOf(1) !== -1 || nums.indexOf(3) !== -1) {
// Return true if either 1 or 3 is found
return true;
} else {
// Return false if neither 1 nor 3 is found
return false;
}
}
// Example usage of the contains13 function
console.log(contains13([1, 5])); // Should return true, as 1 is present
console.log(contains13([2, 3])); // Should return true, as 3 is present
console.log(contains13([7, 5])); // Should return false, as neither 1 nor 3 is present
Output:
true true false
Live Demo:
See the Pen JavaScript - Create a new array taking the middle elements of the two arrays of integer and each length 3 - basic-ex-75 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// ES6 version using arrow function
const contains13 = (nums) => {
return nums.includes(1) || nums.includes(3);
};
// Example usage
console.log(contains13([1, 5]));
console.log(contains13([2, 3]));
console.log(contains13([7, 5]));
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to create a new array taking the first and last elements from a given array of integers and length must be greater or equal to 1.
Next: JavaScript program to test whether an array of integers of length 2 does not contain 1 or a 3.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics