I have an array of numbers
let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104];
I need to return 101
because it broke the sequence, it increased by two.
Thanks.
You can start your for
loop from the 1
to exclude existing checking.
let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104]; const findElement = arr => { for(let i = 1; i < arr.length; i++) { if (arr[i] - arr[i-1] > 1) { return arr[i] } } return false; } console.log(findElement(myNumbers))
You could use find
method and check if prev element is equal to current element - 1.
let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104]; let result = myNumbers.find((e, i, a) => i != 0 && e - 1 != a[i - 1]); console.log(result)
Use simple for
loop and check value of items.
let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104]; for(var i=0; i<myNumbers.length; i++) if (i!=0 && myNumbers[i]>0 && myNumbers[i]-1 != myNumbers[i-1]) console.log(myNumbers[i]);
let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104]; function incrementsBy(n, sequence) { let lastNumber = sequence[0] for(let n of sequence) { if(n - lastNumber > 1) return n lastNumber = n } return null } console.log(incrementsBy(1, myNumbers))
You can use for loop as like below,
function ShowBreak() { let myNumbers = [95, 96, 97, 98, 99, 101, 102, 103, 104] for (i = 0; i < myNumbers.length - 1; i++) { var currentNo = myNumbers[i]; var nextNo = myNumbers[i + 1]; var differents = nextNo - currentNo; if (differents > 1) { console.log(nextNo); return alert("Sequence break on number " + nextNo + " by increase " + differents); } } return alert('Sequence not breaked.'); }
<input type="button" class="btn btn-lg btn-primary btn-block" onclick="ShowBreak()" value="Show" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.