最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove leading zeros in array - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Jul 12, 2020 at 8:07 ledowepledowep 416 bronze badges 1
  • Try to share your code to us could see what is not working. – Isac Moura Commented Jul 20, 2020 at 3:18
Add a ment  | 

7 Answers 7

Reset to default 3

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) : [];
}

Ok, if speed matters, then:

var arr = [0, 0, 0, 14, 0, 63, 0];
function trimLeft(arr) {
  var n = 0;
  for(;n<arr.length&&!arr[n];n++);
  // calling shift every time in loop isn't the
  // fastest way. instead we find the index
  // and slice it from there.
  return arr.slice(n);
}
console.log(trimLeft(arr));

发布评论

评论列表(0)

  1. 暂无评论