Reputation: 801
Suppose i have some key array:
var idlist= [1, 2, 3, 6];
after I was created new object, I need new key/id for it, so i need somethink like this:
fucntion getFirstFreeKey(keylist){
???
}
in my example getFirstFreeKey(idlist) will return 4.
Upvotes: 1
Views: 881
Reputation: 386540
This proposal works with Array#every()
The
every()
method tests whether all elements in the array pass the test implemented by the provided function.
The algorithm looks for consecutive numbers and returns the last one, incremented by one, if a gap is found.
function free(array, start) {
array.every(function (a) {
if (start === a) {
start = a + 1;
return true;
}
});
return start;
}
document.write(free([1, 2, 3, 6], 1) + '<br>'); // 4
document.write(free([1, 2, 3, 4], 1) + '<br>'); // 5
document.write(free([2, 3, 4], 1) + '<br>'); // 1
document.write(free([], 1) + '<br>'); // 1
Upvotes: 3
Reputation: 126
Assuming your list is ordered and you need the next free sequential number:
var freeNum;
for(var i = 0; i < idlist.Length; i++)
{
if(idList[i] != i + 1)
{
freeNum = i + 1;
break;
}
}
return freeNum;
Upvotes: 0