

- 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
Form a sequence out of an array in JavaScript
Suppose we have a sorted array of numbers like this where we can have consecutive numbers.
const arr = [1, 2, 3, 5, 7, 8, 9, 11];
We are required to write a JavaScript function that takes one such array.
Our function should form a sequence for this array. The sequence should be such that for all the consecutive elements of the array, we have to just write the starting and ending numbers replacing the numbers in between with a dash (-), and keeping all other numbers unchanged.
Therefore, for the above array, the output should look like −
const output = '1-3,5,7-9,11';
Example
The code for this will be −
const arr = [1, 2, 3, 5, 7, 8, 9, 11]; const buildSequence = (arr = []) => { let pointer; return arr.reduce((acc, val, ind) => { if (val + 1 === arr[++ind]) { if (pointer == null ) { pointer = val; }; return acc; }; if (pointer) { acc.push(`${pointer}-${val}`); pointer = null; return acc; } acc.push(val); return acc; }, []).join(','); } console.log(buildSequence(arr));
Output
And the output in the console will be −
1-3,5,7-9,11
- Related Questions & Answers
- Can array form consecutive sequence - JavaScript
- Finding the only out of sequence number from an array using JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- Checking if two arrays can form a sequence - JavaScript
- Determining whether numbers form additive sequence in JavaScript
- Get the closest number out of an array in JavaScript
- Filtering out primes from an array - JavaScript
- Picking out uniques from an array in JavaScript
- Find an element in an array such that elements form a strictly decreasing and increasing sequence in Python
- Rearrange an array in maximum minimum form by JavaScript
- Check if the elements of the array can be rearranged to form a sequence of numbers or not in JavaScript
- JavaScript: Check if array has an almost increasing sequence
- Get closest number out of array JavaScript
- Converting array into increasing sequence in JavaScript
- Checking the equality of array elements (sequence dependent) in JavaScript
Advertisements