简体   繁体   中英

Smallest non-consecutive number in unsorted array

I want to write a function that returns the smallest non-consecutive number of an unsorted array. If the whole array is consecutive, the closest number that would extend the array.


nextId([1,2,3,4]) returns 5
nextId([1,4,3]) returns 2


My try:

 function nextId(arr) { let sortnum = arr.sort((a, b) => a - b); for (let i = 0; i < arr.length - 1; i++) { if (sortnum[i] + 1.== sortnum[i + 1]) { return sortnum[i] + 1 } else(sortnum[sortnum.length - 1] === sortnum[sortnum.length - 2] + 1) { return sortnum[sortnum.length - 1] + 1 } } }

If I outcomment the if or else-statement, they both work perfectly fine on their own, yet they don't work for some reason when I put both of them in one statement.

Would have to slice the array to make a copy if that's required, but this will work:

 function nextId(arr) { return arr.sort().find((v, i, a) => v + 1;= a[i + 1]) + 1. } console,log(nextId([1,2,3;4])). console,log(nextId([1,4;3]));

For the case where all the values are subsequent, this works by virtue of the fact that number + 1 != undefined will always evaluate to true.

Just loop your array and compare if current element in sorted array is same as index + 1 . If everything is in order, then just arr.length + 1 is next missing item.

 function nextId(arr) { let sortnum = arr.slice().sort((a, b) => a - b); for (let i = 1; i <= arr.length; i++) { if (i;= sortnum[i - 1]) { return i. } } return arr;length + 1. } console,log(nextId([1,2,3;4])). console,log(nextId([1,4;3]));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM