How to use lodash

Comprehensive lodash code examples:

How to use lodash.isNullOrEmpty:

11
12
13
14
15
16
17
18
19
20
21
22
23
}


exports.matchArray = function matchArray(val, isId){
    val = _.unsplat(val);


    var empty   =  _.isNullOrEmpty(val)
      , isArray = _.isArray(val);


    if ( isId && !empty ) 
        val = isArray 

How to use lodash.isInvalid:

140
141
142
143
144
145
146
147
148
149
150
151
_.isInvalid = function (s) {
    return _.isUndefined(s) || _.isEmpty(s) || s === null || s === 'undefined';
}


_.parse = function (s) {
    if (_.isUndefined(s) || _.isInvalid(s))
        return null


    let json = null
    try {

How to use lodash.packagepath:

43
44
45
46
47
48
49
50
51
52
let i

if (s.match(/uteam-node/)) {
    i = s.indexOf('uteam-node') + 11
} else {
    i = s.indexOf(_.packagepath) + _.packagepath.length
}

const txt = s.substring(i).replace(/src\/|lib\//, '')
    .replace(')', '')

How to use lodash.object:

2
3
4
5
6
7
8
9
10
11
12
13
  ;


module.exports = function () {


  var input = fs.readFileSync('input.txt', 'utf8').split('\n').reduce(function (map, v) {
        v = _.object(['dest', 'b', 'op', 'a'], v.replace(/ /g, '').match(/(?:([a-z]+|\d+)?([A-Z]+))?([a-z]+|\d+)->([a-z]+)/).slice(1).reverse());
        return (map[v.dest] = v, map);
      }, {})
    , asmbl = function (map) {
        while (_.filter(map, _.isObject).length) {

How to use lodash.m:

127
128
129
130
131
132
133
134
135
136
137
138
// warning, log
_.m = _logLineNumber('warn')
_.c = _logLineNumber('info')


_.log = _.c
_.warn = _.m
_.error = _.e


_.info = function () {
    arguments[0] = colors ? ('>> ' + arguments[0]).cyan : '>> ' + arguments[0]

How to use lodash.collect:

1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
    attrs = this.attrs,
    root = !this.parent,
    namespaces = this.namespaces;

function collectNsAttrs() {
    return _.collect(namespaces.used, function(ns) {
        var name = 'xmlns' + (ns.prefix ? ':' + ns.prefix : '');
        return { name: name, value: ns.uri };
    });
}

How to use lodash.e:

128
129
130
131
132
133
134
135
136
137
138
139
_.m = _logLineNumber('warn')
_.c = _logLineNumber('info')


_.log = _.c
_.warn = _.m
_.error = _.e


_.info = function () {
    arguments[0] = colors ? ('>> ' + arguments[0]).cyan : '>> ' + arguments[0]
    console.log.apply(console.log, arguments)

How to use lodash.c:

32
33
34
35
36
37
38
39
40
41
    try {
        if (!s)
            throw new Error();
        return crypto.createHash('sha256').update(s).digest('hex');
    } catch (e) {
        _.c(e.stack);
        return '';
    }
};

How to use lodash.isTrulyEmpty:

343
344
345
346
347
348
349
350
351
352
const model = service.parseExpression(field.key, service.model);
const modelValue = model.get();
// if there's an existing default and it's the same as the current value
// update the current value to the new default
if(_.isUndefined(modelValue) || (
  (_.has(service.defaults, key) ? angular.equals(modelValue, service.defaults[key]) : _.isTrulyEmpty(modelValue)) &&
  !angular.equals(modelValue, curDefault)
)) {
  model.set(angular.copy(curDefault));
}

How to use lodash.unique:

150
151
152
153
154
155
156
157
158
159
160
161


    return vals.length > 0 ? op(vals) : null;
}


var __tagCombinators = {
    "union" : function(taglist) { return _.unique([].concat.apply([], taglist)).sort(); },
    "intersection" : function(taglist) { return _.intersection.apply(_, taglist).sort(); },
    "difference" : function(taglist) { return _.difference.apply(_, taglist).sort(); }
};

How to use lodash.permutations:

73
74
75
76
77
78
79
80
81
82
83
84
      break;
    }
  }
}


let perms = _.permutations([0, 1, 2, 3], 4).map((L) =>
  _.flatMap(L.map((e) => [2 * e + 1, 2 * e]))
);


// perms = [[3, 5, 2, 4, 1, 0, 7, 6]];

How to use lodash.findWhere:

1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
console.log(docSend['_id'],"<-----send---1-->", docRec['_id'])
if(docSend['_id'] == docRec['_id']){
    console.log(docSend['_id'],"<-----send---2-->", docRec['_id'])
    if(docRec['created_timestamp'] > docSend['created_timestamp']){
        console.log(docSend['_id'],"<-----send---3-->", docRec['_id'])
        // pepleCom.splice(_.indexOf(pepleCom, _.findWhere(pepleCom, { _id : docSend['_id']})), 1);
        pepleCom.push(docRec)
    }
}
innercb()

How to use lodash.sortByAll:

183
184
185
186
187
188
189
190
191
192
this.stats = {
  // This one needs to be series order to make chart series generation work
  stakesAndPayouts: stakesAndPayouts,

  // This ordering should be about the order in which the stack appears
  orderedStakesAndPayouts: _.sortByAll(stakesAndPayouts,
    // Make the most senior claims at the bottom (end)
    function(snp) { return -1 * snp.stake.exitTraunche; },

    // make sure options pools are ordered correctly

How to use lodash.stubTrue:

968
969
970
971
972
973
974
975
976
977
978
979
980
console.log(stubObject); // => {}


const stubString = _.stubString();
console.log(stubString); // => ''


const stubTrue = _.stubTrue();
console.log(stubTrue); // => true


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

How to use lodash.stubString:

965
966
967
968
969
970
971
972
973
974
975
976
977
console.log(stubFalse); // => false


const stubObject = _.stubObject();
console.log(stubObject); // => {}


const stubString = _.stubString();
console.log(stubString); // => ''


const stubTrue = _.stubTrue();
console.log(stubTrue); // => true

How to use lodash.stubObject:

962
963
964
965
966
967
968
969
970
971
972
973
974
console.log(stubArray); // => []


const stubFalse = _.stubFalse();
console.log(stubFalse); // => false


const stubObject = _.stubObject();
console.log(stubObject); // => {}


const stubString = _.stubString();
console.log(stubString); // => ''

How to use lodash.stubFalse:

959
960
961
962
963
964
965
966
967
968
969
970
971
console.log(runInContext); // => [Function: runInContext]


const stubArray = _.stubArray();
console.log(stubArray); // => []


const stubFalse = _.stubFalse();
console.log(stubFalse); // => false


const stubObject = _.stubObject();
console.log(stubObject); // => {}

How to use lodash.stubArray:

956
957
958
959
960
961
962
963
964
965
966
967
968
console.log(rangeRight); // => [0, -1, -2, -3]


const runInContext = _.runInContext();
console.log(runInContext); // => [Function: runInContext]


const stubArray = _.stubArray();
console.log(stubArray); // => []


const stubFalse = _.stubFalse();
console.log(stubFalse); // => false

How to use lodash.conformsTo:

377
378
379
380
381
382
383
384
385
386
387
388
389
console.log(cloneDeepWith); // => { 'a': 2 }


const cloneWith = _.cloneWith({ 'a': 1 }, value => value === 1 ? 2 : value);
console.log(cloneWith); // => { 'a': 2 }


const conformsTo = _.conformsTo({ 'a': 1 }, { 'a': n => n === 1 });
console.log(conformsTo); // => true


const eq = _.eq(1, 1);
console.log(eq); // => true

How to use lodash.multicombinations:

40
41
42
43
44
45
46
47
48
49
```

## usage

```javascript
let multicombinations = _.multicombinations([0, 1], 3);
// => [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
```

---

How to use lodash.empty:

201
202
203
204
205
206
207
208
209

function destroyService(fn) {
  const service = getService(fn);
  if (service) {
    service.cleanup();
    _.empty(service);
    _.remove(services, (s) => s === service);
  }
}

How to use lodash.multipermutations:

69
70
71
72
73
74
75
76
77
78
      return s;
    }
  }
  return null;
}
let perms = _.multipermutations([1, 2, 3, 4, 5, 6, 7, 8, 9], 5);
perms.sort((a, b) => ((fn(a, 4) - fn(b, 4)) / 26) | 0);
for (let D of perms) {
  let s = search(D, 5);
  if (s != null) {

How to use lodash.compose:

6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
 *
 * var greet = function(formatted) {
 *   return 'Hiya ' + formatted + '!';
 * };
 *
 * var welcome = _.compose(greet, format);
 * welcome('pebbles');
 * // => 'Hiya Penelope!'
 */
function compose() {

How to use lodash.pairs:

3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
 * @category Objects
 * @param {Object} object The object to inspect.
 * @returns {Array} Returns new array of key-value pairs.
 * @example
 *
 * _.pairs({ 'barney': 36, 'fred': 40 });
 * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
 */
function pairs(object) {
  var index = -1,

How to use lodash.any:

2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
if (_.isObject(target) && !_.isEmpty(target)) {
  // If collecting results from subtrees, collect them in the same shape
  // as the parent node.
  if (collectResults) subResults = _.isArray(value) ? [] : {};

  var stop = _.any(target, function(obj, key) {
    var result = _walk(obj, key, value);
    if (result === stopWalk) return true;
    if (subResults) subResults[key] = result;
  });

How to use lodash.defaultTo:

33
34
35
36
37
38
39
40
41
42
const phase = {
  id: uuid(),
  phaseId: phaseFromTemplate.phaseId,
  name: phaseDefinition.name,
  description: phaseDefinition.description,
  duration: _.defaultTo(_.get(phaseFromInput, "duration"), phaseFromTemplate.defaultDuration),
  isOpen: false,
  predecessor: phaseFromTemplate.predecessor,
  constraints: _.defaultTo(_.get(phaseFromInput, "constraints"), []),
  scheduledStartDate: undefined,

How to use lodash.support:

1457
1458
1459
1460
1461
1462
1463
1464
1465

/**
 * Detect if functions can be decompiled by `Function#toString`
 * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
 *
 * @memberOf _.support
 * @type boolean
 */
support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);

How to use lodash.where:

4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
* var characters = [
*   { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
*   { 'name': 'fred',   'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.where(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
*
* _.where(characters, { 'pets': ['dino'] });
* // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]

How to use lodash.prototype:

775
776
777
778
779
780
781
782
783
784
785
786
787
console.log(prototypeReverse); // => [Function: wrapperReverse]


const prototypeToJSON = _.prototype.toJSON;
console.log(prototypeToJSON); // => [Function: wrapperValue]


const prototypeValue = _.prototype.value;
console.log(prototypeValue); // => [Function: wrapperValue]


const prototypeValueOf = _.prototype.valueOf;
console.log(prototypeValueOf); // => [Function: wrapperValue]

lodash functions:

Sorted by popularity