w3resource

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:

JavaScript: Test whether an array of integers of length 2 contains 1 or a 3.

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:

Flowchart: JavaScript - Test whether an array of integers of length 2 contains 1 or a 3

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]));

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that tests whether a two-element array contains either the number 1 or 3.
  • Write a JavaScript function that checks an array of length 2 for the presence of 1 or 3, returning a boolean result.
  • Write a JavaScript program that inspects a two-number array and outputs a message indicating if it contains 1 or 3.

Go to:


PREV : Create Array with First/Last Elements from Array.
NEXT : Check if Array Does Not Contain 1 or 3.

Improve this sample solution and post your code through Disqus.

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.