How to use the compact function from lodash

Find comprehensive JavaScript lodash.compact code examples handpicked from public code repositorys.

lodash.compact is a function in the Lodash library used to create a new array with all falsey values removed.

2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
if (that.templateRequestsQueue.length() === 0) {
	resolve({ errors: {}, schemas: {} });
	that.templateRequestsQueue = undefined;
} else {
	that.templateRequestsQueue.drain = function () {
		var errors = _.compact(_.pluck(that.templateRequestsResults.errors, "typeid"));
		var results = that.templateRequestsResults;
		var resultsKeys = Object.keys(that.templateRequestsResults.schemas);
		var tempMissingDependencies = [];
		let tempConstant;
fork icon439
star icon0
watch icon75

4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
 * @category Arrays
 * @param {Array} array The array to compact.
 * @returns {Array} Returns a new array of filtered values.
 * @example
 *
 * _.compact([0, 1, false, 2, '', 3]);
 * // => [1, 2, 3]
 */
function compact(array) {
  var index = -1,
fork icon73
star icon711
watch icon29

How does lodash.compact work?

lodash.compact is a function provided by the Lodash library used to create a new array with all falsey values removed. When lodash.compact is called, it takes as input an array and returns a new array with all falsey values removed. In this context, "falsey" means any value that is considered false when used in a boolean context, such as null, undefined, false, 0, NaN, or an empty string (""). The function works by iterating over each element in the input array and checking if it is a falsey value. If the element is truthy, meaning it is not falsey, it is added to the new array. If the element is falsey, it is skipped and not added to the new array. lodash.compact is often used in JavaScript applications to filter out falsey values from an array, making it easier to work with only the values that are actually meaningful. By providing a simple and efficient way to filter out falsey values, compact makes it easier to write clean and maintainable JavaScript code.

106
107
108
109
110
111
112
113
114
115
116
  const items = [
    itemCount(this.stats.albums, 'album'),
    itemCount(this.stats.photos, 'photo'),
    itemCount(this.stats.videos, 'video')
  ]
  this.summary = _.compact(items).join(', ')
}


Album.prototype.sort = function (options) {
  const sortAlbumsBy = getItemOrLast(options.sortAlbumsBy, this.depth)
fork icon80
star icon649
watch icon20

+ 4 other calls in file

56
57
58
59
60
61
62
63
64
65
module.exports.clone               = _.clone;
module.exports.cloneDeep           = _.cloneDeep;
module.exports.cloneDeepWith       = _.cloneDeepWith;
module.exports.cloneWith           = _.cloneWith;
module.exports.collate             = _.collate;
module.exports.compact             = _.compact;
module.exports.comparator          = _.comparator;
module.exports.complement          = _.complement;
module.exports.concat              = _.concat;
module.exports.cond                = _.cond;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

Ai Example

1
2
3
4
5
6
const _ = require("lodash");

const array = [0, 1, false, 2, "", 3, null, undefined, NaN, 4];
const result = _.compact(array);

console.log(result); // [1, 2, 3, 4]

In this example, we first import the lodash library. We then define an array with ten elements, including several falsey values such as 0, false, '', null, undefined, and NaN. We then call _.compact with the array as input, which returns a new array with all falsey values removed. We store the resulting array in the result variable and log it to the console, which shows that the only remaining elements are the truthy values 1, 2, 3, and 4. By using _.compact, we can easily remove falsey values from an array, making it easier to work with only the values that are actually meaningful. This can be particularly useful when dealing with arrays of user input, where there may be many falsey values that need to be filtered out.

344
345
346
347
348
349
350
351
352
performance: {
  // Silence warnings because the size includes the sourcemaps
  maxEntrypointSize: 15_120_000,
  maxAssetSize: 15_120_000,
},
plugins: compact([
  produceSourcemap &&
    new webpack.SourceMapDevToolPlugin({
      publicPath: sourceMapPublicUrl,
fork icon21
star icon66
watch icon4

90
91
92
93
94
95
96
97
98
99
  oldcitycode: voie.codeAncienneCommune,
  lon: voie.lon,
  lat: voie.lat,
  x: voie.x,
  y: voie.y,
  city: compact([getNomCommune(codeCommuneArrondissement), commune.nom, voie.nomAncienneCommune]),
  district: codeCommuneArrondissement ? commune.nom : undefined,
  oldcity: voie.nomAncienneCommune,
  context: buildContext(getCodeDepartement(commune.code))
}
fork icon3
star icon7
watch icon3

+ 3 other calls in file

358
359
360
361
362
363
364
365
366
    for (let key in objekt) updateFileFields(objekt[key], objekt, key, mappedAssetUids, matchedUids, unmatchedUids);
  } else if (_.isArray(objekt) && objekt.length) {
    for (let i = 0; i <= objekt.length; i++)
      updateFileFields(objekt[i], objekt, i, mappedAssetUids, matchedUids, unmatchedUids);


    parent[pos] = _.compact(objekt);
  }
}
fork icon10
star icon4
watch icon12

+ 3 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14
15
// Array


const chunk = _.chunk(['a', 'b', 'c', 'd'], 2);
console.log(chunk); // => [['a', 'b'], ['c', 'd']]


const compact = _.compact([0, 1, false, 2, '', 3]);
console.log(compact); // => [1, 2, 3]


const concat = _.concat([1], 2, [3], [[4]]);
console.log(concat); // => [1, 2, 3, [4]]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

206
207
208
209
210
211
212
213
214
215
216
217
      default:
        break;
    }
  }


  return { result: _.compact(validFields), id };
};


const filterFieldValidation = (filter, field, locale, ownership) => {
  field.locale === 'auto' ? field.locale = 'en-US' : null;
fork icon0
star icon3
watch icon3

+ 11 other calls in file

475
476
477
478
479
480
481
482
483
      toDelete.push(entry.id);
    }
  });
}

toDelete = _.compact(_.uniq(toDelete));

if (!commits.length && !toDelete.length) {
  log.info('Nothing to commit.');
fork icon3
star icon1
watch icon2

+ 4 other calls in file

80
81
82
83
84
85
86
87
88
89
    return acc;
  }

  acc[method] = {
    ...requestInfo,
    parameters: _.compact(_.concat(parameters, requestInfo.parameters)),
  };

  return acc;
},
fork icon236
star icon0
watch icon12

91
92
93
94
95
96
97
98
99
100
if (err) {
  logger.error(JSON.stringify(err));
  return h.response(err).code(err.code);
}

const pathways = _.compact(
  pathways_order.map((pathway_code) => _.find(data, { code: pathway_code }))
);

let pathway;
fork icon18
star icon15
watch icon4

+ 2 other calls in file

155
156
157
158
159
160
161
162
163
164
  line = subscriberNumber.substring(3);
}

const normal =
  nationalSignificantNumber
    ? _.compact([nationalSignificantNumber, extension]).join('x')
    : raw;

const phone = new String(normal);
phone.prefix = nationalPrefix;
fork icon0
star icon1
watch icon16

+ 7 other calls in file

920
921
922
923
924
925
926
927
928
929
930
931
  }
  return initiatetables
}


async function authorizecollection (username) {
  const S3Foldersarray = _.compact(S3Folders.split(';'))


  // if not match Logverz-MasterController than check user authorization for given s3 folders.
  if (username.match('Logverz-MasterController') === null) {
    const usertype = 'UserAWS'
fork icon0
star icon1
watch icon0

7
8
9
10
11
12
13
14


    if (_.startsWith(url, '#') || _.startsWith(url, 'http://') || _.startsWith(url, 'https://')) {
        return url;
    }
    const basePath = _.trim(pathPrefix, '/');
    return '/' + _.compact([basePath, _.trimStart(url, '/')]).join('/');
}
fork icon0
star icon1
watch icon0

71
72
73
74
75
76
77
78
79
80

  var type = utils.sqlTypeCast(attribute.autoIncrement ? 'SERIAL' : attribute.type);
  var nullable = attribute.notNull && 'NOT NULL';
  var unique = attribute.unique && 'UNIQUE';

  return _.compact([ '"' + name + '"', type, nullable, unique ]).join(' ');
}).join(',');

var primaryKeys = _.keys(_.pick(obj, function (attribute) {
  return attribute.primaryKey;
fork icon0
star icon0
watch icon0

+ 2 other calls in file

85
86
87
88
89
90
91
92
93
94
for (const color of [void 0, ...Object.keys(paint)]) {
  for (const serializeAs of [void 0, "json", "yaml"]) {
    if (color || serializeAs)
      _.set(
        log,
        _.compact([color, serializeAs]),
        (...args) => _log({ color, serializeAs }, ...args)
      );
  }
}
fork icon0
star icon0
watch icon1

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
  res_limit = (data.request.limit < queryRes_Max) ? data.request.limit : (queryRes_Max);
}

const filtersOnConfig = ['medium', 'subject', 'gradeLevel'];
const filters = {};
filters[Op.and] = _.compact(_.map(data.request.filters, (value, key) => {
  const res = {};
  if (filtersOnConfig.includes(key)) {
    res[Op.or] = _.map(data.request.filters[key], (val) => {
      delete data.request.filters[key];
fork icon0
star icon0
watch icon1

+ 11 other calls in file

267
268
269
270
271
272
273
274
275
276
try {
  let contents = [];
  let tableData = [];
  let response = resData[0].data;
    if (response && response.result && (_.get(response.result, 'content')|| _.get(response.result, 'QuestionSet'))) {
      contents = _.compact(_.concat(_.get(response.result, 'QuestionSet'), _.get(response.result, 'content')));
    }
    if (contents.length) {
      tableData = _.map(_.filter(contents, (c)=> {
        if (c.status === 'Live' || (c.status === 'Draft' && c.prevStatus === 'Live')) {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

8
9
10
11
12
13
14
15
16
17
18
19
20
// console.log(newArr)


// let arr2 = _.chunk(arr, 5);
// console.log(arr2)


// _.compact(array)
// Creates an array with all falsey values removed. 
// The values false, null, 0, "", undefined, and NaN are falsey.


// let arr = [1,2,3,4,5, 0, false,6, null, undefined, "", 7,8];
fork icon0
star icon0
watch icon1

+ 11 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)