Javascript - How Do I Check if 3 Numbers Are Consecutive and Return Starting Points?
It'd be interesting to know the context of this task as well... Anyway, here's my solution:
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var results = [];
var limit = arr.length - 1;
var sequence = 0;
for (var i = 0; i < limit; ++i) {
var diff = arr[i+1] - arr[i];
if (sequence && sequence === diff) {
results.push(i-1);
continue;
}
sequence = (diff === 1 || diff === -1) // or ... Math.abs(diff) === 1
? diff
: 0;
}
console.log(results);
The idea is simple: we don't need to compare two neighbors twice. ) It's enough to raise a kind of sequence flag if this comparation starts a sequence, and lower it if no sequence is there.
Check consecutive numbers in array javascript
You can use reduce with the initial value as the first element of the array
const checkIsConsecutive = (array) =>
Boolean(array.reduce((res, cur) => (res ? (Number(res.value) + 1 === Number(cur.value) ? cur : false) : false)));
console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '4' }]));
console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '5' }]));
Find the specific consecutive set of numbers in a Javascript array
Perhaps you could do something like the following:
const numbers = [0,0,0,296,296,0,0,296,296,296,0,0,0,0,0,293,293,293,293,293,293,293,293,91];
function findConsecCount(value) { var startIndex = -1 var result = 0 for(var i = 0; i < numbers.length; i++) { if(numbers[i] === value) { if(startIndex === -1) { startIndex = i } } if(numbers[i] !== value) { if(startIndex !== -1) { result = Math.max(result, i - startIndex) startIndex = -1; } } } if(numbers[numbers.length - 1] === value) { if(startIndex !== -1) { result = Math.max(result, i - startIndex) startIndex = -1; } } return { key : value, longestConsecutive : result }}
console.log( findConsecCount(0) )console.log( findConsecCount(293) )console.log( findConsecCount(296) )console.log( findConsecCount(91) )
check if elements in array are consecutive --- javascript
One sidenote is that you want to call it multiple times, so each call should know which array it's working on and what the previous offset
in that array was. One thing you can do is to extend the native Array
object. [Demo]
Array.prototype.nextCons = (function () {
var offset = 0; // remember the last offset
return function () {
var start = offset, len = this.length;
for (var i = start + 1; i < len; i++) {
if (this[i] !== this[i-1] + 1) {
break;
}
}
offset = i;
return this[start];
};
})();
Usage
var arr = [1,2,3,4,6,8,9];
arr.nextCons(); // 1
arr.nextCons(); // 6
arr.nextCons(); // 8
Compare 2 or more consecutive numbers in an array
Perhaps what would actually be useful is the groups:
const findGroups = (arr) => arr.reduce((result, value, index) => {
let windowLength = 2;
while (arr[index + windowLength - 1] === value) {
result.push(arr.slice(index, index + windowLength));
windowLength++;
}
return result;
}, []);
console.log(findGroups([2, 2, 0, 0, -1, 1, -1, -1, -1])); // [[2, 2], [0, 0], [-1, -1], [-1, -1, -1], [-1, -1]]
console.log(findGroups([4, 4, 4, 4])); // [[4, 4], [4, 4, 4], [4, 4, 4, 4], [4, 4], [4, 4, 4], [4, 4]]
Finding the greatest amount of consecutive values in an array (JS)
You can use one value to keep count of consecutive false values and if that value is larger then current max set max value to that value. If value is true
you reset counter to 0
.
var arr = [false, false, true, false, true, false, true, false, false, false]var c = 0, max = 0;
arr.forEach(function(e) { e == false ? c++ : c = 0; if (c > max) max = c;})
console.log(max)
How to Make Consecutive Numbers from an Array
Below I created function for replacing a sequence in an array with a string containing its range. There are three functions.
getConsectiveCount
will take array and index as arguments and will get the count of consecutive numbers after that.
replaceFirstConsective
will take array and will replace only first sequence in the array.
replaceAllConsectives
will replace all the sequences in an array.
const arr = [-2,4,5,6,7,8,10,11,15,16,17,18,21];
const getConsectiveCount = (arr, index) => {
let count = 0;
for(let i = index; i < arr.length; i++){
if(arr[i + 1] === arr[index] + (i - index) + 1){
count++;
}
}
return count;
}
console.log(getConsectiveCount(arr, 1));
const replaceFirstConsective = (arr) => {
for(let i = 0; i < arr.length; i++){
let count = getConsectiveCount(arr,i);
if(count){
return [...arr.slice(0, i), `${arr[i]}-${arr[i + count]}`, ...arr.slice(i + count + 1)]
}
}
return arr;
}
const replaceAllConsectives = (arr) => {
for(let i = 0; i < arr.length;i++){
arr = replaceFirstConsective(arr)
}
return arr;
}
console.log(JSON.stringify(replaceAllConsectives(arr)))
How can I find all first indexes of sequence of consecutive zeroes in an array?
First I would like to recommend that you use more descriptive variable names. The fact that you need to describe what each of them means, means that they are not descriptive enough.
Also your variable N
seems redundant, because arrays already have a .length
property that you can use to see how many elements are in there.
The source of your error seems to be that you use a nested loop. There is no need to use nested loops. You only need to go through all elements once and keep track of the repeated zeroes. Every time you encounter a non-zero value, you reset the sequence count to 0
. If do encounter a zero you increment the sequence count and afterwards you check if the sequence count is equal to the number of zeroes you passed as an argument. In that case you want to push the first index to the resulting array and reset the sequence count to 0
again.
function getFirstIndexesOfSequenceOfConsecutiveZeroes(input, numberOfRepeatedZeroes) {
if (numberOfRepeatedZeroes <= 0) {
throw new Error("numberOfRepeatedZeroes need to be 1 or higher");
}
var firstIndexes = [];
let sequenceStartIndex;
let sequenceCount = 0;
for (var i = 0; i < input.length; i++) {
if (input[i] !== 0) {
sequenceCount = 0;
} else {
if (sequenceCount == 0) {
sequenceStartIndex = i;
}
sequenceCount++;
}
if (sequenceCount === numberOfRepeatedZeroes) {
firstIndexes.push(sequenceStartIndex);
sequenceCount = 0;
}
}
return firstIndexes;
}
let input = [1, 0, 0, 1];
let numberOfRepeatedZeroes = 1;
console.log(getFirstIndexesOfSequenceOfConsecutiveZeroes(input, numberOfRepeatedZeroes));
Related Topics
How to Get the Latest and Oldest Record in Mongoose.Js (Or Just the Timespan Between Them)
Text Input Allow Only Integer Input in Angularjs
Image Upload With Preview and Delete Option - Javascript/Jquery
Show 2 Items Per Row[React Native]
Javascript Onclick Increment Number
How to Convert Seconds to Minutes and Hours in JavaScript
How to Set an Iframe Src Attribute from a Variable in Angularjs
Javascript/Dom: How to Remove All Event Listeners of a Dom Object
Modify Classname When Element Is Clicked in React
Basic Open Source JavaScript Image Editor
Getting Selected Values from Dropdown Inside Table
How to Remove Row Borders in a Specific Column
Javascript (+) Sign Concatenates Instead of Giving Sum of Variables
Using Js Remove Comma from Number from Existing Data
Ajax - How to Use a Returned Array in a Success Function
Get the Value of Datepicker on Change in Jquery
Prevent Bootstrap Modal Window from Closing on Form Submission