Following is my code, in which I am trying to reduce the size of each array item by 2 and once the particular value of an array becomes 0 or -1 I will replace it with undefined.
Example -
Input - [5,4,4,2,2,8]
Output -
Array Non Blank Values
5 4 4 2 2 8 6
3 2 2 _ _ 6 4
1 _ _ _ _ 4 2
_ _ _ _ _ 3 1
_ _ _ _ _ _ DONE
Code (Somehow its going as an infinite loop)-
var arr = [5,4,4,2,2,8]; // 6 4 2 1
var num = 0;
itemNum = countItemNotUndefined(arr);
function makeItemUndefine(arr) {
return arr.map(function(x){
x = x - 2;
return x ==0 || x == -1 ? undefined : x;
})
}
function countItemNotUndefined(arr) {
var itemLength = 0;
arr.map(function(x){
if(x !== undefined)
itemLength++;
})
return itemLength;
}
while(itemNum != 0) {
num ++;
var result = makeItemUndefine(arr);
itemNum = countItemNotUndefined(result);
}
console.log("Number is ", num);
Let me know what I am doing wrong here.
itemNumnever changesitemNumtozeroby passing the result incountItemNotUndefined(arr)