w3resource

JavaScript: Check downward trend, array of integers

JavaScript Math: Exercise-93 with Solution

Write a JavaScript program to check if an array of integers has a downward trend or not.

Test Data:
([1, 3, 4, 7, 9, 10, 11]) -> false
([11, 10, 9, 7, 4, 3, 2, 0]) -> true
([1, 0, -2, -3, -12]) -> true

Sample Solution:

JavaScript Code:

/**
 * Function to check if the elements in the array are in descending order.
 * @param {number[]} nums - The array to be checked.
 * @returns {boolean} - Returns true if the array is in descending order, false otherwise.
 */
function test(nums) {
    return nums.every((item, i) => item > nums[i + 1] || item === nums[nums.length - 1]);
}

// Test cases
let nums = [1, 3, 4, 7, 9, 10, 11];
console.log("n = " + nums);
console.log("Process: " + test(nums));
nums = [11, 10, 9, 7, 4, 3, 2, 0];
console.log("n = " + nums);
console.log("Process: " + test(nums));
nums = [1, 0, -2, -3, -12];
console.log("n = " + nums);
console.log("Process: " + test(nums));

Output:

n = 1,3,4,7,9,10,11
 process: false
n = 11,10,9,7,4,3,2,0
 process: true
n = 1,0,-2,-3,-12
 process: true

Flowchart:

JavaScript: Check downward trend, array of integers.

Live Demo:

See the Pen javascript-math-exercise-93 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Iterated Cube Root.
Next: Even, odd numbers and their sum in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/javascript-exercises/javascript-math-exercise-93.php