
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
Odd Even Index Difference in JavaScript
We are required to write a JavaScript function that takes in an array of numbers like this −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8];
The function should return the difference between the sum of elements present at the odd index and the sum of elements present at even index
Example
Following is the code −
const arr = [3, 6, 34, 12, 6, 8, 8, 5, 6, 8]; const oddEvenDiff = arr => { let diff = 0; for(let i = 0; i < arr.length; i++){ if(i % 2 === 0){ diff += arr[i]; }else{ diff -= arr[i] }; }; return Math.abs(diff); }; console.log(oddEvenDiff(arr));
Output
This will produce the following output in console −
18
Advertisements