

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
All possible odd length subarrays JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only input.
The function picks all possible odd length subarrays from the original array, calculate their sum and return the total sum.
Note that by subarray, we mean a contiguous subsequence of the array and not any possible combination of numbers.
For example -
If the input array is −
const arr = [1, 2, 3, 4, 5];
Then all possible odd length arrays will be −
[1], [2], [3], [4], [5], [1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4, 5]
And their total sum will be −
const output = 57
Example
const arr = [1, 2, 3, 4, 5]; const sumArray = (arr = []) => arr.reduce((a, b) => a + b); const oddSum = (arr = []) => { let len = 1; let sum = 0; const { length } = arr; while(len <= length){ for(let i = 0; i + len <= length; i++){ sum += sumArray(arr.slice(i, i + len)); }; len += 2; }; return sum; }; console.log(oddSum(arr));
Output
This will produce the following output −
57
- Related Questions & Answers
- Sum of All Possible Odd Length Subarrays in JavaScript
- Program to find sum of all odd length subarrays in Python
- Reverse only the odd length words - JavaScript
- Smallest possible length constituting greatest frequency in JavaScript
- Merging subarrays in JavaScript
- Find the Length of the Longest possible palindrome string JavaScript
- Program to find sum of medians of all odd length sublists in C++
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Count subarrays with same even and odd elements in C++
- Find the Number of Subarrays with Odd Sum using C++
- Generating all possible permutations of array in JavaScript
- All possible binary numbers of length n with equal sum in both halves?
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Find the Number of Subarrays with m Odd Numbers using C++
- Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)
Advertisements