
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If an Array is Growing by the Same Margin in JavaScript
We are required to write a JavaScript function that takes in an array of numbers. Our function should return true if the difference between all adjacent elements is the same positive number, false otherwise.
Example
The code for this will be −
const arr = [4, 7, 10, 13, 16, 19, 22]; const growingMarginally = arr => { if(arr.length <= 1){ return true; }; const diff = arr[1] - arr[0]; if(diff < 0){ return false; } for(let i = 0; i < arr.length - 1; i++){ if (arr[i+1] - arr[i] !== diff){ return false; } } return true; }; console.log(growingMarginally(arr));
Output
And the output in the console will be −
true
Advertisements