简体   繁体   English

删除数组中的前导零

[英]Remove leading zeros in array

Example arrays:示例 arrays:

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

Wanted arrays:想要 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.我尝试使用filter方法.filter(val => val)但它从数组中删除所有零。

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

 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.因为我们将变量声明为闭包 function 的参数,我们将其初始化为 false,所以我们可以保存 var/let/const 语句。

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.您可以关闭last ,这对于第一个 falsy 值是false的。

 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.使用 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.一旦你得到它,只需开始推送结果数组中元素的 rest 并返回它。

 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

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或作为原型 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您可以使用Array.prototype.findIndex()找到具有非零值的第一个索引,然后使用Array.prototype.slice()获取元素的 rest

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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