0

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.

3
  • why wouldn't it run forever? itemNum never changes Commented May 3, 2016 at 19:59
  • @vsync I am trying to reduce the itemNum to zero by passing the result in countItemNotUndefined(arr) Commented May 3, 2016 at 20:01
  • It looks like result is reset to the original array every time it loops rather than using the modified array from the previous loop. Commented May 3, 2016 at 20:02

1 Answer 1

3

The problem is that you're calling makeItemUndefine on arr, which doesn't change, since you assign the result to a different variable called result. So you aren't actually reducing the numbers in the array over time.

The correct solution would be:

while(itemNum != 0) {
    num ++;
    arr = makeItemUndefine(arr);
    itemNum = countItemNotUndefined(arr);
}

Another problem with the code is the fact that you're trying to subtract from undefined numbers, which turns them, into NaN's. There are two solutions to this, either check for NaN inside of countItemNotUndefined, or check for undefined inside of the map.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.