Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding the sum of floors covered by an elevator in JavaScript
Problem
We are required to write a JavaScript function that takes in an array that represents the floor numbers at which a building lift stopped during an interval of time.
From that data, our function should return the count of total number of floors covered by the lift in that time.
Example
Following is the code −
const arr = [7, 1, 7, 1];
const floorsCovered = (arr = []) => {
let res = 0;
for (let i = 0; i < arr.length; i++){
if (arr[i] > arr[i+1]){
res += arr[i] - arr[i+1];
};
if (arr[i] < arr[i+1]){
res += arr[i+1] - arr[i];
}
};
return res;
};
console.log(floorsCovered(arr));
Output
Following is the console output −
18
Advertisements
