How to use the filter function from underscore

Find comprehensive JavaScript underscore.filter code examples handpicked from public code repositorys.

underscore.filter is a JavaScript function that returns an array of elements from the given collection that pass the specified test.

562
563
564
565
566
567
568
569
570
571
      }
    }
  });
}
function getParticipants(docId, excludeClosed, excludeUserId, excludeViewer) {
  return _.filter(connections, function(el) {
    return el.docId === docId && el.isCloseCoAuthoring !== excludeClosed &&
      el.user.id !== excludeUserId && el.user.view !== excludeViewer;
  });
}
fork icon171
star icon146
watch icon32

+ 3 other calls in file

517
518
519
520
521
522
523
524
525
526
clickMenu(card, menuText) {
    if(_.isString(card)) {
        card = this.findCardByName(card);
    }

    var items = _.filter(card.getMenu(), item => item.text === menuText);

    if(items.length === 0) {
        throw new Error(`Card ${card.name} does not have a menu item "${menuText}"`);
    }
fork icon18
star icon17
watch icon0

+ 5 other calls in file

How does underscore.filter work?

underscore.filter is a higher-order function in the Underscore.js library that takes a collection and a predicate function, then returns a new collection with only the elements that satisfy the predicate function. When called, underscore.filter iterates over each element in the input collection and applies the predicate function to it. If the function returns true for that element, it is included in the output collection. If the function returns false, the element is excluded from the output. The output collection is a new array or object, depending on the type of the input collection. The original input collection is not modified by this operation.

460
461
462
463
464
465
466
467
468
469
470
    if (result instanceof Warning) {
      // In case something serious was caught, let's remove the throw
      t.markedForDeletion = true
    }
  })
  throws = _.filter(throws, t => !t.markedForDeletion)


  //console.log('THROWS:\n' + JSON.stringify(throws))
}

fork icon2
star icon5
watch icon1

+ 11 other calls in file

9825
9826
9827
9828
9829
9830
9831
9832
9833

// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
  var rest = flatten(arguments, true, true, 1);
  return _.filter(array, function(value){
    return !_.contains(rest, value);
  });
};
fork icon1
star icon1
watch icon2

+ 39 other calls in file

Ai Example

1
2
3
4
5
6
7
8
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = _.filter(numbers, function (num) {
  return num % 2 === 0;
});

console.log(evenNumbers);
// Output: [2, 4, 6, 8, 10]

In this example, we first define an array of numbers from 1 to 10. We then use _.filter() to create a new array evenNumbers that only contains the even numbers from numbers. We pass in a callback function as the second argument to _.filter(), which takes a single argument num and returns a boolean indicating whether num is even or not. Finally, we log evenNumbers to the console to verify that it only contains the even numbers from the original numbers array.

2316
2317
2318
2319
2320
2321
2322
2323
2324
2325

// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
  var rest = slice.call(arguments, 1);
  return _.filter(_.uniq(array), function(item) {
    return _.every(rest, function(other) {
      return _.indexOf(other, item) >= 0;
    });
  });
fork icon0
star icon1
watch icon1

+ 7 other calls in file

33
34
35
36
37
38
39
40
41
42
	ttf: _.template('url("<%= url %>") format("truetype")'),
	svg: _.template('url("<%= url %>#<%= fontName %>") format("svg")')
}

// Order used types according to 'options.order'.
var orderedTypes = _.filter(options.order, function(type) {
	return options.types.indexOf(type) !== -1
})

var src = _.map(orderedTypes, function(type) {
fork icon0
star icon1
watch icon1

323
324
325
326
327
328
329
330
331
332
};

var leafTotal = function (leafName) {
  var total = 0;
  _.each(
    _.filter(entries, function (entry) {
      return isLeaf(entry) && entryName(entry) === leafName;
    }),
    function (leaf) {
      total += entryTime(leaf);
fork icon0
star icon7
watch icon4

+ 17 other calls in file

2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
                } catch (err) {
                    return reject(err);
                }
            })
    );
    const contributors = _.filter(await Promise.all(promises));
    return resolve(contributors);
} catch (err) {
    return reject(err);
}
fork icon0
star icon2
watch icon0

801
802
803
804
805
806
807
808
809
810
};
ChatroomController.exitGroupChatRoom(exitdata, function (err, resp) {
  console.log("!!!!!!!!!!!!!!!!!!!",resp)
 });
console.log("socket user %%%%%%%%%%%%",socket.users)
let filteredRoomUser = _.filter(socket.users, function (roomUserObj) {
   // if (roomUserObj.userId != data.user.userId) {
  //   return roomUserObj;
  // }
});
fork icon0
star icon1
watch icon0

787
788
789
790
791
792
793
794
795
796
  return slice.call(array, (index == null) || guard ? 1 : index);
};

// Trim out all falsy values from an array.
_.compact = function(array) {
  return _.filter(array, function(value){ return !!value; });
};

// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
fork icon0
star icon0
watch icon0

+ 5 other calls in file

308
309
310
311
312
313
314
315
316
317
* @private
* @param {object} policies  A map of policy id's to an object containing username password ws-trust endpoint addresses.
*/
Mex.prototype._selectSingleMatchingPolicy = function(policies) {
  // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists.
  var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; });
  if (!matchingPolicies) {
    this._log.warn('no policies found with an url');
    return;
  }
fork icon0
star icon0
watch icon0

35
36
37
38
39
40
41
42
43
44
 * @param  {Array}   entries  An array of cache entries to remove.
 * @param  {Function} callback This function is called when the operation is complete.  Any error is provided as the
 *                             first parameter.
 */
MemoryCache.prototype.remove = function(entries, callback) {
  var updatedEntries = _.filter(this._entries, function(element) {
    if (_.findWhere(entries, element)) {
      return false;
    }
    return true;
fork icon0
star icon0
watch icon0

51
52
53
54
55
56
57
58
59
60
    this.render();
}
filteredData() {
    if(_.isArray(this.data) && this.searchQuery) {
        var filteredRegExp = new RegExp(this.searchQuery, 'i');
        var filteredData = _.filter(this.data, function(dict) { return _.values(dict).join(' ').match(filteredRegExp); });
        return filteredData;
    } else {
        return this.data;
    }
fork icon0
star icon0
watch icon2

49
50
51
52
53
54
55
56
57
58
    ;[projectId, docId] = Array.from(line.split(' '))
    result1.push({ doc_id: docId, project_id: projectId })
  }
  return result1
})()
pending = _.filter(result, row =>
  __guard__(row != null ? row.doc_id : undefined, x =>
    x.match(/^[a-f0-9]{24}$/)
  )
)
fork icon0
star icon0
watch icon202

+ 5 other calls in file

52
53
54
55
56
57
58
59
60
61
if(filters._id && filters._id.$ne){
    if(!_.isArray(filters._id.$ne)){
        filters._id.$ne = [filters._id.$ne]
    }
    for(let neid of filters._id.$ne){
        workflowNotifications = _.filter(workflowNotifications, function(item){
            return item._id !== neid
        })
    }
}
fork icon0
star icon0
watch icon1

+ 4 other calls in file

61
62
63
64
65
66
67
68
69
70
if(filters._id && filters._id.$ne){
    if(!_.isArray(filters._id.$ne)){
        filters._id.$ne = [filters._id.$ne]
    }
    for(let neid of filters._id.$ne){
        actionFieldUpdates = _.filter(actionFieldUpdates, function(item){
            return item._id !== neid
        })
    }
}
fork icon0
star icon0
watch icon1

+ 2 other calls in file

52
53
54
55
56
57
58
59
60
61
if(filters._id && filters._id.$ne){
    if(!_.isArray(filters._id.$ne)){
        filters._id.$ne = [filters._id.$ne]
    }
    for(let neid of filters._id.$ne){
        messages = _.filter(messages, function(item){
            return item._id !== neid
        })
    }
}
fork icon0
star icon0
watch icon1

+ 4 other calls in file

25
26
27
28
29
30
31
32
33
afterFind: async function(){
    if(this.spaceId === 'template'){
        let filters = internalData.parserFilters(this.query.filters)
        let flowDatas = getFlows();
        if(filters.category){
            flowDatas = _.filter(flowDatas, function(flow){
                return flow.category === filters.category
            })
        }
fork icon0
star icon0
watch icon1

+ 3 other calls in file

135
136
137
138
139
140
141
142
143
144
    }

    layouts = await getInternalLatouts(layouts, filters);
    
    if(layouts){
        this.data.values = this.data.values + _.filter(layouts, function(layout){return layout._id && layout._id.indexOf('.') > 0 }).length
    }
},
afterFindOne: async function(){
    if(_.isEmpty(this.data.values)){
fork icon0
star icon0
watch icon1