JavaScript: Check whether 1 appears in first or last position of a given array of integers
JavaScript Basic: Exercise-71 with Solution
Write a JavaScript program to check whether 1 appears in the first or last position of a given array of integers. The array length must be larger than or equal to 1.
The program verifies if the number 1 is present at either the first or last position of an array of integers, ensuring the array's length is at least 1. If the condition is met, it returns true; otherwise, it returns false.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named first_last_1 with a parameter nums
function first_last_1(nums)
{
// Calculate the index of the last element in the array
var end_pos = nums.length - 1;
// Check if the first or last element in the array is equal to 1, and return the result
return nums[0] == 1 || nums[end_pos] == 1;
}
// Call the function with sample arguments and log the results to the console
console.log(first_last_1([1, 3, 5]));
console.log(first_last_1([1, 3, 5, 1]));
console.log(first_last_1([2, 4, 6]));
Output:
true true false
Live Demo:
See the Pen JavaScript - Check whether 1 appears in first or last position of a given array of integers - basic-ex-71 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named first_last_1 with a parameter nums using arrow function syntax
const first_last_1 = nums => {
// Use the logical OR operator to check if the first or last element of the array is equal to 1
return nums[0] === 1 || nums[nums.length - 1] === 1;
};
// Call the function with sample arguments and log the results to the console
console.log(first_last_1([1, 3, 5]));
console.log(first_last_1([1, 3, 5, 1]));
console.log(first_last_1([2, 4, 6]));
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to rotate the elements left of a given array of integers of length 3.
Next: JavaScript program to check whether the first and last elements are equal of a given array of integers length 3.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-basic-exercise-71.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics