Javascript Array compact()

Description

Javascript Array compact()


// Returns a copy of the array with all falsy values removed.
// In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

var array = [0, 1, false, 2, '', 3, null, undefined, NaN];

Array.prototype._compact = function(){
  return this.filter(function(i){
    return i;//  w ww .  ja  v  a2 s.  c  o m
  });
};

array._compact();
// [1, 2, 3]

Javascript Array compact()


Array.prototype.compact = function() {
 var results = [];
 for (var i = 0, len = this.length; i < len; i++) {
  if (this[i] != null) {
   results.push(this[i]);/*  ww  w  .  j  ava2 s . com*/
  }
 }
 
 return results;
};

Javascript Array compact()

// refactored (requires Enumerable)
Array.prototype.compact = function() {
 return this.select(function(value) {
  return value != null;
 });//from  w ww  .  j ava 2 s.co m
};

Javascript Array compact()


// Compact (array)
// ---------------
// Removes falsy values
Array.prototype.compact = function() {
  return this.filter(function(item) {
    return !!item;
  });//from   w  w  w  .  j av a 2 s  . c o  m
}

Javascript Array compact()

Array.prototype.compact = function()
{
    var a = [];//from   w w w .ja v a  2  s .c  o  m
    for( var i = 0; i < this.length; i++ ) {
        if( i in this ) 
            if( this[ i ] != "" ) a.push( this[ i ] );
    }
    return a;
};

Javascript Array compact()


// Array/*from  w w w . j a va  2 s. c  om*/
Array.prototype.compact = function(){
    var ca = [];

    for(var i in this){
        if (this.hasOwnProperty(i)) {
            if ( present(this[i]) ) {
                ca.push(this[i]);
            }
        }
    }

    return ca;
};

Javascript Array compact()


Array.prototype.compact = function() {
  return this.reduce(function(res, el) {
    if(el !== null) {
      res.push(el);//from ww  w .  ja  v  a2s.  c om
    };
    return res;
  }, [])
}



PreviousNext

Related