Home > Mobile >  Javascript Array Count and delete zero's
Javascript Array Count and delete zero's

Time:04-07

I have an Array let test = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7]

I need to count the amount of zero's from the starting point in this case "9" upto value 3

Next want to only delete the first nine entries . The remaining zero's in the rest of the array must remain.

Expected Result

Count = 9 Let Test = [3,4,5,6,3,0,0,0,0,4,6,7]

CodePudding user response:

First of all, the result of your example should be Count = 10 because there are 10 of 0.

I suppose you want to define a function to get the result. That can be:

const func = (arr) => {
    let count = 0
    for (let i in arr) {
        if (arr[i] != 0) {
            break
        }
        count  
    }
    return [count, arr.slice(count)]
}

// Test:
const array = [0,0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7]
console.log(`Count = ${func(array)[0]}, Array = ${func(array)[1]}`)
// Result should be Count = 10, Array = [3,4,5,6,3,0,0,0,0,4,6,7]

CodePudding user response:

Please try the following code :

function firstZeros(r) {

    var c = 0,s=true,nr=[];
    for(let ri of r){
        if(s && ri==0){
            c  ;
        }else{
            s=false;        
            nr.push(ri);
        }
    }
    
    return {'count':c,'data':nr};
}


let test = [0,0,0,0,0,0,0,0,0,3,4,5,6,3,0,0,0,0,4,6,7];

let res = firstZeros(test);

console.log('Count=' res.count);
console.log('Test=' res.data);

Thanks

  • Related