- 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

# Algorithm to sum ranges that lie within another separate range in JavaScript

We have two sets of ranges; one is a single range of any length (R1) and the other is a set of ranges (R2) some or parts of which may or may not lie within the single range (R1).

We need to calculate the sum of the ranges in (R2) - whole or partial - that lie within the single range (R1).

const R1 = [20,40]; const R2 = [[14,22],[24,27],[31,35],[38,56]];

**Result **

= 2+3+4+2 = 11

R1 = [120,356]; R2 = [[234,567]];

**Result **

122

## Example

Let us write the code −

const R1 = [20,40]; const R2 = [[14,22],[24,27],[31,35],[38,56]]; const R3 = [120,356]; const R4 = [[234,567]]; function sumRanges(range, values) { const [start, end] = range; const res = values.reduce((acc, val) => { const [left, right] = val; const ex1 = Math.min(right, end); const ex2 = Math.max(left, start); const diff = ex1 - ex2; return acc + Math.max(0, diff); }, 0); return res; }; console.log(sumRanges(R1, R2)); console.log(sumRanges(R3, R4));

## Output

And the output in the console will be −

11 122

- Related Questions & Answers
- How to find the percentage of values that lie within a range in R data frame column?
- How to find the percentage of values that lie within a range in a single column R matrix?
- Count BST subtrees that lie in given range in C++
- Print missing elements that lie in range 0 – 99
- Finding sum of all numbers within a range in JavaScript
- How to find the percentage of values that lie within a range in column of a data.table object in R?
- Count BST nodes that lie in a given range in C++
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Prime numbers within a range in JavaScript
- Armstrong number within a range in JavaScript
- Converting a comma separated string to separate arrays within an object JavaScript
- Find a range that covers all the elements of given N ranges in C++
- Generating desired pairs within a range using JavaScript
- Finding sequential digit numbers within a range in JavaScript
- Find pairs with given sum such that pair elements lie in different BSTs in Python

Advertisements