How to use the each function from underscore
Find comprehensive JavaScript underscore.each code examples handpicked from public code repositorys.
underscore.each is a function in the Underscore.js library that iterates over each element in a collection and executes a given function on it.
GitHub: cliss/camel
282 283 284 285 286 287 288 289 290
var sortedKeys = _.sortBy(_.keys(groupedFiles), function (date) { return new Date(date); }).reverse(); // For each day... _.each(sortedKeys, function (key) { if (new Date(key) > new Date()) { return; }
+ 77 other calls in file
GitHub: ONLYOFFICE/server
3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
var changes = data.changes; if (null == changes) { objChangesDocument = yield* getDocumentChanges(ctx, data.docId, data.startIndex, data.changesIndex); changes = objChangesDocument.arrChanges; } _.each(participants, function(participant) { if (!needSendChanges(participant)) { return; } sendData(ctx, participant, {type: 'saveChanges', changes: changes,
+ 19 other calls in file
How does underscore.each work?
Underscore's each() function iterates over a given list of elements and performs a function for each element in the list, passing the element and its index into the function. The function can be either provided as an argument or it can be a method of an object.
449 450 451 452 453 454 455 456 457 458
const isObject = val => typeof val === 'object' && !Array.isArray(val); const paths = (obj = {}) => { _.each(obj, function(value, key) { isObject(value) ? f.loop(value, action) : action(obj, key) });
+ 14 other calls in file
469 470 471 472 473 474 475 476 477 478
} }; // loop through mixins object and attach their handler methods // to res.locals['mixin-name']. _.each(mixins, function (mixin, name) { const handler = _.isFunction(mixin.handler) ? mixin.handler : function () { return function (key) { this.options = this.options || {}; this.options.fields = this.options.fields || {};
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12
const numbers = [1, 2, 3, 4, 5]; _.each(numbers, function (num) { console.log(num); }); // Output: // 1 // 2 // 3 // 4 // 5
In this example, _.each is used to iterate over each element in the numbers array and log its value to the console. The first argument to _.each is the array to iterate over, and the second argument is the function to call for each element.
GitHub: Ashteki/ashteki
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
// check for a game state change (recalculating conflict skill if necessary) if (this.effectEngine.checkEffects(hasChanged) || hasChanged) { this.checkWinCondition(); // if the state has changed, check for: for (const player of this.getPlayers()) { _.each(player.cardsInPlay, (card) => { if (card.getModifiedController() !== player) { // any card being controlled by the wrong player this.takeControl(card.getModifiedController(), card); }
+ 7 other calls in file
GitHub: GeraldWodni/kern.js
858 859 860 861 862 863 864 865 866 867
if( err ) next( err ); else res.json( data ); }); }); /* wheres, currently only supported for sql, if needed can be extended by handling readWhere in unPrefixedCrud */ _.each( crud.wheres, function( where, name ) { var url = fsPath.join( opts.path, "where", name ); where.parameters.forEach( function( parameter ) { url = fsPath.join( url, ":" + parameter.name );
+ 35 other calls in file
GitHub: wotcity/automationjs
171 172 173 174 175 176 177 178 179 180
// Apply a method on every element in the container, // passing parameters to the call method one at a // time, like `function.apply`. apply: function(method, args){ _.each(this._elements, function(elem){ if (_.isFunction(elem[method])){ elem[method].apply(elem, args || []); } });
+ 5 other calls in file
6230 6231 6232 6233 6234 6235 6236 6237 6238 6239
return result(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result(this, method.apply(this._wrapped, arguments)); };
+ 9 other calls in file
GitHub: gristlabs/grist-core
111 112 113 114 115 116 117 118 119 120
* * Note: Commands to the aceEditor are always enabled. * Note: Ace defers to standard behavior when false is returned. */ AceEditor.prototype.attachCommandGroup = function(commandGroup) { _.each(commandGroup.knownKeys, (command, key) => { this.editor.commands.addCommand({ name: command, // We are setting readonly as true to enable all commands // in a readonly mode.
+ 2 other calls in file
GitHub: sdarnell/meteor-win
210 211 212 213 214 215 216 217 218 219
var globalMain; if ('main' in global) { mains.push(main); globalMain = main; } typeof Package !== 'undefined' && _.each(Package, function (p, n) { if ('main' in p && p.main !== globalMain) { mains.push(p.main); } });
+ 3 other calls in file
737 738 739 740 741 742 743 744 745 746
defenders = this.filterUnableToParticipate(defenders, conflictType); if(defenders.length === 0) { throw new Error(`None of the specified attackers can participate in ${conflictType} conflicts`); } _.each(defenders, card => { this.clickCard(card); }); } this.clickPrompt('Done');
+ 31 other calls in file
GitHub: sdarnell/meteor-win
193 194 195 196 197 198 199 200 201 202
// contains exact duplicates. var mostSpecificMatch = function (host, programs) { var seen = {}; var best = null; _.each(programs, function (p) { if (seen[p]) throw new Error("Duplicate architecture: " + p); seen[p] = true; if (archinfo.matches(host, p) &&
+ 9 other calls in file
GitHub: Ashteki/ashteki
460 461 462 463 464 465 466 467 468 469
return this.triggeredAbility(AbilityType.ForcedReaction, properties); } applyAnyLocationPersistentEffects() { _.each(this.persistentEffects, (effect) => { if (effect.location === 'any') { effect.ref = this.addEffectToEngine(effect); } });
GitHub: physiocoder/meteor
68 69 70 71 72 73 74 75 76
// Display a message showing valid Meteor architectures. var showInvalidArchMsg = function (arch) { Console.info("Invalid architecture: " + arch); Console.info("The following are valid Meteor architectures:"); _.each(_.keys(VALID_ARCHITECTURES), function (va) { Console.info(" " + va); }); };
+ 7 other calls in file
GitHub: yonas/meteor-freebsd
322 323 324 325 326 327 328 329 330 331
return _.union(_.map(_.filter(entries, isLeaf), entryName)); }; var leafTotal = function (leafName) { var total = 0; _.each( _.filter(entries, function (entry) { return isLeaf(entry) && entryName(entry) === leafName; }), function (leaf) {
+ 41 other calls in file
69 70 71 72 73 74 75 76 77 78
var parts = path.normalize(relPath).split(path.sep); if (parts.length > 1 && parts[parts.length - 1] === '') parts.pop(); // remove trailing slash var partsSoFar = []; _.each(parts, function (part) { partsSoFar.push(part); var partial = partsSoFar.join(path.sep); if (! (partial in self.usedAsFile)) { // It's new -- create it
+ 5 other calls in file
427 428 429 430 431 432 433 434 435 436
var namedTypes = {}; if (!_.has(protocol, 'protocol') || !_.isString(protocol.protocol)) { throw new InvalidProtocolError('Protocol must contain a "protocol" attribute with a string value'); } if (_.isArray(protocol.types)) { _.each(protocol.types, function(typeSchema) { var schemaValidator = new Validator(typeSchema, protocol.namespace, namedTypes); var fullyQualifiedTypeName = makeFullyQualifiedTypeName(typeSchema, protocol.namespace); _typeSchemaValidators[fullyQualifiedTypeName] = schemaValidator; });
GitHub: peerlibrary/meteor
205 206 207 208 209 210 211 212 213 214
}, end: function () { var self = this; _.each(_.keys(self.buffers), function (channel) { if (self.buffers[channel].text.length) { self.lines.push({ channel: channel, text: self.buffers[channel].text, bare: true });
GitHub: Cloud-V/Backend
477 478 479 480 481 482 483 484 485 486
.find({ repo: repo._id, deleted: false, }) .exec(); _.each(ips, (ip) => { ip.deleted = true; ip.save().exec().catch(console.error); }); } catch (err) {
+ 3 other calls in file
GitHub: Dev1an/meteor
153 154 155 156 157 158 159 160 161 162
JSON.stringify(error) + "; " + error.message)); return; } var ret = []; _.each(stdout.split('\n'), function (line) { // Matches mongos we start. Note that this matches // 'fake-mongod' (our mongod stub for automated tests) as well // as 'mongod'. var m = line.match(/^\s*(\d+).+mongod .+--port (\d+) --dbpath (.+)(?:\/|\\)\.meteor(?:\/|\\)local(?:\/|\\)db/);
+ 7 other calls in file
underscore.keys is the most popular function in underscore (11266 examples)