
- 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
Check if items in an array are consecutive but WITHOUT SORTING in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n, as the second argument.
Our function should check if there is a sequence of n (taken as the second argument) or more consecutive numbers in the array but without sorting the array.
For example, if our input array is −
const arr = [0, 4, 6, 5, 9, 8, 9, 12]; const n = 3;
Then our function should return true because there exist three consecutive numbers 4, 5, and 6 in the array.
Example
The code for this will be −
const arr = [0, 4, 6, 5, 9, 8, 9, 12]; const n = 3; const findSequence = (arr, num) => { if(num > arr.length){ return false; }; let count = 1; for(let i = 0; i < arr.length; i++){ let el = arr[i]; while(arr.includes(++el)){ count++; if(count === num){ return true; }; }; count = 1; }; return false; }; console.log(findSequence(arr, n)); console.log(findSequence(arr, 4));
Output
And the output in the console will be −
true false
- Related Questions & Answers
- Check if array elements are consecutive in Python
- Check if three consecutive elements in an array is identical in JavaScript
- Sorting Array without using sort() in JavaScript
- Count unique elements in array without sorting JavaScript
- Fetch Second minimum element from an array without sorting JavaScript
- JavaScript to check consecutive numbers in array?
- Check if Queue Elements are pairwise consecutive in Python
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Alternative sorting of an array in JavaScript
- JavaScript - Check if array is sorted (irrespective of the order of sorting)
- Sorting an integer without using string methods and without using arrays in JavaScript
- Sorting an array of objects by an array JavaScript
- Sorting an associative array in ascending order - JavaScript
- Sorting an array that contains undefined in JavaScript?
Advertisements