w3resource

JavaScript: Check whether 1 appears in first or last position of a given array of integers

JavaScript Basic: Exercise-71 with Solution

Check if 1 is First/Last Element in Array

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:

JavaScript: Check whether 1 appears in first or last position of a given array of integers.

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:

Flowchart: JavaScript - Check whether 1 appears in first or last position of a given array of integers

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

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that checks whether the number 1 appears as either the first or last element in an array.
  • Write a JavaScript function that inspects an array and returns true if its first or last element equals 1, false otherwise.
  • Write a JavaScript program that validates the array’s length before determining if 1 is positioned at the beginning or end.

Go to:


PREV : Rotate Elements Left in Array (Length 3).
NEXT : Check if First and Last Elements Are Same.

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.