- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Sum odd indexed and even indexed elements separately and return their absolute difference
We are required to write a JavaScript function that takes in an array of numbers. The function should sum odd indexed and even indexed elements separately and finally should return their absolute difference.
Example
const arr = [4, 6, 3, 1, 5, 8, 9, 3, 4]; const oddEvenDifference = (arr = []) => { let oddSum = 0; let evenSum = 0; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(i % 2 === 0){ evenSum += el; }else{ oddSum += el; }; }; return Math.abs(oddSum - evenSum); }; console.log(oddEvenDifference(arr));
Output
And the output in the console will be −
7
- Related Articles
- Absolute Difference of even and odd indexed elements in an Array (C++)?
- Absolute Difference of even and odd indexed elements in an Array in C++?
- Sorting odd and even elements separately JavaScript
- Program to find number of elements can be removed to make odd and even indexed elements sum equal in Python
- Converting Odd and Even-indexed characters in a string to uppercase/lowercase in JavaScript?
- Program to find only even indexed elements from list in Python
- Indexed collections in JavaScript
- How to remove the 0th indexed element in an array and return the rest of the elements in JavaScript?
- Calculate the difference between the first and second element of each subarray separately and return the sum of their differences in JavaScript
- PHP Indexed Array
- Print all n-digit numbers with absolute difference between sum of even and odd digits is 1 in C++
- How to access datetime indexed elements in pandas series?
- Odd even index difference - JavaScript
- Maximum Sum Increasing Subsequence using Binary Indexed Tree in C++
- What are hashed files and indexed file organization(DBMS)?

Advertisements