javascript - How to dynamically grab the first available number in a loop? -
been going @ while, figured i'd post here help.
items = { '417': { a: 23, slot_position: 13 }, '419': { a: 28, slot_position: 2 }, '420': { a: 29, slot_position: 12 }, '421': { a: 29, slot_position: 3 }, '424': { a: 31, slot_position: 17 }, '425': { a: 32, slot_position: 7 }, '428': { a: 35, slot_position: 0 }, '429': { a: 36, slot_position: 0 }, '431': { a: 42, slot_position: 0 }, '432': { a: 40, slot_position: 0 }, '433': { a: 43, slot_position: 11 }, '434': { a: 44, slot_position: 0 }, '435': { a: 45, slot_position: 0 }, '436': { a: 47, slot_position: 0 }, '437': { a: 48, slot_position: 15 }, '438': { a: 48, slot_position: 1 }, '439': { a: 48, slot_position: 0 }, '440': { a: 48, slot_position: 14 }, '441': { a: 43, slot_position: 0 }, '442': { a: 44, slot_position: 0 }, '443': { a: 43, slot_position: 8 }, '444': { a: 37, slot_position: 0 }, '445': { a: 37, slot_position: 0 }, '446': { a: 37, slot_position: 0 }, '447': { a: 37, slot_position: 16 }, '451': { a: 50, slot_position: 5 }, '452': { a: 49, slot_position: 6 }, '453': { a: 39, slot_position: 20 }, '454': { a: 38, slot_position: 4 }, '455': { a: 19, slot_position: 19 }, '456': { a: 49, slot_position: 9 }, '457': { a: 51, slot_position: 0 } }; inventory_slots = 30; used_slots = []; for(a in items){ if(items[a].slot_position > 0){ used_slots.push(items[a].slot_position); } } console.log(used_slots);
see on jsfiddle: http://jsfiddle.net/sf71l5jq/6/
so, user has 30
available inventory slots. , above console logs array:
[13, 2, 12, 3, 17, 7, 11, 15, 1, 14, 8, 16, 5, 6, 20, 4, 19, 9]
how go finding first open number (slot)? in case, should 10. how accomplish dynamically?
edit: @tim lewis's idea here: http://jsfiddle.net/sf71l5jq/8/ doesn't catch correct number. (note: not saying idea wrong, it's code).
for(i=1; < inventory_slots; i++){ if(used_slots[i] != i){ first_open = used_slots[i]; // why first_open assigned '2'? break; } }
first of all, values need sorted in numeric order:
used_slots.sort(sortnumber); function sortnumber(a, b){ return - b; }
next, loop through using counter , find first index
doesn't match counter
:
for(i = 0; < inventory_slots; i++){ if(used_slots[i] != i+1){ first_open = i+1; break; } } console.log(first_open); // 10
in case, first open slot 10
. note, index starts @ 0
, not 1
, slot numbers start @ 1
, explains comparison if(used_slots[i] != i+1)
, assignment first_open = i+1;
Comments
Post a Comment