简体   繁体   中英

Remove leading zeros in array

Example arrays:

[0, 0, 0, 14, 0, 63, 0]
[243, 0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0]
[0]

Wanted arrays:

[14, 0, 63, 0]
[243, 0, 0, 0, 1]
[1, 0]
[]
[]

I tried using filter method .filter(val => val) but it remove all zeros from array.

This is all you need.

 const arr = [0, 0, 0, 14, 0, 63, 0]; while (arr.indexOf(0) === 0) { arr.shift() } console.log(arr)

Extract to a function

 function leftTrim(array, trimBy = 0) { // prevents mutation of original array const _array = [...array]; while (_array.indexOf(trimBy) === 0) { _array.shift() } return _array; } // trim left by 0 (default) console.log(leftTrim([0, 0, 1, 0, 1, 0])); // trim left by 1 console.log(leftTrim([1, 1, 1, 1, 0, 1, 0], 1));

And here as a public service the internals of the accepted answer:
Two words: Closure-functions !

Normally, we know the filter-function as such

/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];

So now we have this statement:

filter = array => array.filter((last => v => last = last || v)(false));

Which expands to:

filter = array => array.filter(
    function(last)
    {
        return function(v)
        {
             return last = last || v;
        };
    }(false)
);

Which expands further to:

filter = function(array)
{
       return array.filter(
             function(last)
             {
                    return function(v)
                    {
                           return last = last || v;
                    }
             }
             (false)
       );
};

And now we see the trick:
Instead of a global-variable, we declare a variable in a closure-function.
Because we declare the variable as an argument to the closure function, which we initialize with false, we can save us the var/let/const-statement.

Hooray to arrow-functions !
With their help, it's much more evident what happens...
(okay, granted, maybe i should use them more;) )

You could take a closure over last which is false for the first falsy values.

 const filter = array => array.filter((last => v => last = last || v)(false)); console.log(filter([0, 0, 0, 14, 0, 63, 0])); console.log(filter([243, 0, 0, 0, 1])); console.log(filter([0, 0, 1, 0])); console.log(filter([0, 0])); console.log(filter([0]));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Simple solution using while. Easy to understand in single loop. You need to loop till you get first non zero element. Once you get that just start pushing the rest of elements in result array and return it.

 function removeLeadingZeros(arr){ let i=0; let result =[]; while(arr[i]===0){ i++; } while(i<arr.length){ result.push(arr[i]); i++; } console.log(result); } removeLeadingZeros([0,0,0,14,0,6,0]);

as a function

function removeLeading = function(char, arr) {
    let finish = false;
    return arr.filter(i => {
        if (finish) return true;
        
        if (i != char) finish=  true;
        return i != char;
    })
} 
removeLeading(0, [0, 0, 0, 14, 0, 63, 0])

or as prototype function

Array.prototype.removeLeading = function(char) {
    let finish = false;
    return this.filter(i => {
        if (finish) return true;
        
        if (i != char) finish=  true;
        return i != char;
    })
} 
[0, 0, 0, 14, 0, 63, 0].removeLeading(0)

You can find the first index having a non zero value using Array.prototype.findIndex() and then use Array.prototype.slice() to get the rest of the elements

const removeLeadingZeroes = (arr) => {
    const index = arr.findIndex(Boolean);
    return index !== -1 ? arr.slice(index) : [];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM