FAQ Database Discussion Community


The lodash way to delete nested array elements

javascript,arrays,underscore.js,lodash
I have an array like: [[0,1,2,3][0,1,2,3,][0,1,2,3][0,1,2,3]] I want to slice the nested arrays to keep only the first two elements. I am using this code with lodash: for (i = 0; i < data.length; ++i) { data[i] = _.slice(data[i], [start=0], [end=2]); } This doesn't feel very lodash though. How would...

In underscore/lodash, how to avoid duplicate calculation in a `map` method?

javascript,functional-programming,underscore.js,lodash
Here is my code: var transformed = _(original).map(function (c) { return { lat: wgs2gcj(c.latitude, c.longitude).lat lng: wgs2gcj(c.latitude, c.longitude).lng } }); Let's say wgs2gcj is a function from a third-party library and will take a long time to compute. Is there a way to do the calculation only once?...

lodash/underscore; compare two objects and remove duplicates

javascript,json,object,underscore.js,lodash
As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data. exact_match : {104} match_4 : {104, 103} match_2 : {104, 103, 68} How can I "trim" or remove the duplicate objects based on previous ones? something...

combining performing _.uniq with _.isEqual in lodash

lodash
lodash provides a method _.uniq() to find unique elements from an array, but the comparison function used is strict equality ===, while I want to use _.isEqual(), which satisfies: _.isEqual([1, 2], [1, 2]) // true Is there a way to perform _.uniq() with _.isEqual(), without writing my own method?...

Make new array that fills in missing values using lodash

javascript,arrays,date,lodash
I have an array of objects which have a property of date in milliseconds. Note that the first three objects have the same date, but a different value. var data = [ {"date":"1420070400000","value":53,"lat":"41.8089","lon":"-88.0111","regType":"Client","jobRole":"Other"}, {"date":"1420070400000","value":376,"lat":"41.8089","lon":"-88.0111","regType":"Client","jobRole":"Other"}, {"date":"1420070400000","value":43,"lat":"41.8089","lon":"-88.0111","regType":"Client","jobRole":"Other"},...

Merging/Joining 2 array objects on attribute in lodash

javascript,node.js,lodash
Is it possible to merge two array object based on an attribute present in both arrays. I would like to achieve this via lodash lib. eg Consider a list of catogories with id as PK and a list of movies with catagoryId as a FK Array of movie category: [{...

Get an element of an array no matter the size of the index

javascript,arrays,lodash
It exists some library with a function that allow me to do something like the code example I post bellow? I search without success and Lodash doesn't have such a method. Maybe it'll be nice to add it to their API. Thanks in advance. var array = [1, 2, 3,...

How to use lodash.mixin in TypeScript

typescript,lodash
My team is evaluating switching some of our files to TypeScript from JavaScript, and we make extensive use of some custom mixin methods in our code. From doing some basic tests, it seems that while we can use _.mixin to create mixins as per the norm, we cannot reference them...

lodash npm distribution in browser

npm,karma-runner,bower,lodash
I'm using lodash in my tests, Not using webpack or browserify (don't need to). I found that the default npm build differs from what's in bower. I could of course use bower version, but I'm curious if I can use npm's instead (it's already there for Gulp). For bower I...

How to combine values in array by key?

javascript,angularjs,underscore.js,lodash
I have data that looks like this: data = [ [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]} ], [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]} ], [ {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]}, {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]} ] ]; how would I use map to combine the array items so the data attributes are concatenated? Like so: data = [ [...

Lodash - “FAQS” should display as “FAQs”

javascript,html,angularjs,lodash
I am using lodash - A JavaScript utility library - with my AngularJS code. <div ng-repeat="question in questions"> <label>{{question | startCase}}</label> </div> This is the documentation for startCase https://lodash.com/docs#startCase I have many questions - approximately 1000. If a question has the word FAQS it should display as FAQs. How can...

lodash searchIndex on reverse sorted list

javascript,lodash
I have a sorted array as follows: var array = [ 10, 10, 10, 8, 7, 6, 6, 6, 6 ]; I want to find the insertion index of 11. Given that this array is sorted in descending order, the insertion index should be 0. Is there a way to...

lodash / underscore.js function to create array consisting of n copies of x

javascript,arrays,underscore.js,lodash
I suspect the reason I am asking this question is the fact that my vocabulary lacks a better term for the function I am looking for and thus I am failing to locate it on google and the lodash API documentation. Do underscore and lodash provide a dedicated function that...

How to use _lodash to retrieve value from Objects in Array?

javascript,arrays,loops,lodash
Here is my Array containing Objects, each Object has a ticker value: [Object] 0: Object $$hashKey: "object:130" tags: Array[1] ticker: Object company: "Alcoa Inc." direction: "negative" percent: -3.89 price: 14.59 selected: true ticker: "AA" There could be several objects, how would one use the _lodash library to pull out the...

Why can't I seem to merge a normal Object into a Mongo Document?

node.js,mongodb,mongoose,underscore.js,lodash
I have a data feed from a 3rd party server that I am pulling in and converting to JSON. The data feed will never have my mongoDB's auto-generated _ids in it, but there is a unique identifier called vehicle_id. The function below is what is handling taking the data-feed generated...

Find object by match property in nested array

lodash
I'm not seeing a way to find objects when my condition would involve a nested array. var modules = [{ name: 'Module1', submodules: [{ name: 'Submodule1', id: 1 }, { name: 'Submodule2', id: 2 } ] }, { name: 'Module2', submodules: [{ name: 'Submodule1', id: 3 }, { name: 'Submodule2',...

React child component receiving props as undefined

reactjs,lodash,react-jsx
I have component Comp1 and it's child Comp2. The state of markers is set in the parent component to this object: var MARKER_ITEMS = { "item1" : { "cat" : "wow", "img" : "slide", "info" : "bike", "key" : "1" }, "item2" : { "cat" : "omg", "img" : "slide",...

How do you filter an array of objects for undefined values?

javascript,arrays,object,underscore.js,lodash
I have the following array: [{object}, {object}, {object}] Each object looks something like: {key0: 3, key1: undefined, key2: 7} I want to filter the array for undefined properties so that each object in the array now looks like: {key0: 3, key2: 7} I've tried everything with Lo_Dash and I'm thinking...

How can I use lodash in dojo?

dojo,lodash
Is there a module for lodash that I can import into my dojo project? I know that I can always reference it by window._, but I wanted to be more conventional (as far as dojo is concerned) and formally require it into my module. Thanks in advance....

Write a function to iterate and pluck an inner array's objects

javascript,arrays,lodash
How could I use vanilla js or lodash to return Scene.data[i].trends into a one newArr Output should look like this: var newArr = superFunction(); console.log(newArr); => [{id:100},{id:101},{id:200},{id:201}] Dataset: Scenes.data = [ { id: 0, trends: [ { id: 100, }, { id: 101, }] }, { id: 2, trends: [...

Why isn't this lodash uniq isSorted not working?

javascript,lodash
So, I would expect this to sort, but it isn't. _.uniq(array, [isSorted], [iteratee], [thisArg]) so _.uniq([10,3,13,1,0,2], true); I run that, and it doesn't sort. I'd expect it to return: [0,1,2,3,10,13]...

Remap properties name and values using lodash

javascript,underscore.js,lodash
I have this array: aItems = [{ "PropertyA": "apple", "PropertyB": "banana", "PropertyC": "dog", "PropertyD": "hotdog", "PropertyE": "coldcat", "PropertyF": "Y", "PropertyG": "N" }, ..., { "PropertyA": "this", "PropertyB": "is", "PropertyC": "json", "PropertyD": "code", "PropertyE": "wow", "PropertyF": "N", "PropertyG": "N" }] I would like use lodash to obtain this result: aItems =...

lodash/underscore find objects by key that is in values of array

javascript,underscore.js,lodash
I have this array of objects: [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2' }, { id: 3, name: 'test 3' }, { id: 4, name: 'test 4' } ] I have this array of IDs: [1, 3] How can I select all objects...

Filtering one JSON attribute against another with Lodash or Angular

json,lodash
I'm looking for the fastest and most elegant way to do this. I've seen similar questions asked and they're all very specific to a problem. I'm fairly new with Lodash, and I've used _.find mostly. I'm not sure how to use _.filter to get what I want, a new JSON...

Remove elements in array from array using lodash

javascript,arrays,lodash
I want to remove users in the removeUser array based on userName values in the removeUser array using lodash. Here's my input data: {"users":[ {"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"[email protected]", "userName" : "jdoe", "groups": [{"name": "Manager"}]}, {"title":"Ms", "firstName":"Anna", "lastName":"Smith","email":"[email protected]", "userName" : "asmith", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}, {"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"[email protected]", "userName"...

How to filter keys of an object with lodash?

javascript,filter,lodash
I have an object with some keys, and I want to only keep some of the keys with their value? I tried with filter: var data = { "aaa":111, "abb":222, "bbb":333 }; var result = _.filter(data, function(value, key) { return key.startsWith("a"); }) console.log(result); But it prints an array: [111, 222]...

How to dynamically name my object params in this lodash loop?

javascript,loops,for-loop,lodash
https://lodash.com/docs#find var params = {}; _.forEach(n.tags, function(n, index) { console.log(index); index++ // For each tag, create new param.term1, term2, term3 etc... params.term[index] = _.result(_.find(n.tags, function(term_id) { return term_id; }), 'term_id'); }); The _.forEach will loop over n.tags (which contains up to 3 tags). I iterate the index++ by 1 so...

Why does lodash `_.all([true, true, true], true);` return `false`?

javascript,lodash
How can I check if all elements of an array are truthy or falsey. Since the following doesn't seem to do it: _.all([true, true, true], true); it returns: false?...

Lodash equivalent of hoek.reach (hapijs)?

javascript,lodash,hapijs
Hoek.reach solves an interesting and age-old problem of javascript object traversing: https://github.com/hapijs/hoek#reachobj-chain-options. Example: var chain = 'a.b.c'; var obj = {a : {b : { c : 1}}}; Hoek.reach(obj, chain); // returns 1 I want just this functionality of Hoek and nothing else. Just wondering if this functionality is in...

Does lodash or underscore each method run in parallel in Node.js?

javascript,node.js,underscore.js,lodash
I know that in node everything runs in parallel, except your code. Read here and here. I’m looking a possible scenario where I have a very large array in memory and I want to perform a small computation to each of its elements. The order in which this computation executes...

jQuery change event not firing on dynamically created element [duplicate]

javascript,jquery,lodash,listjs
This question already has an answer here: Event binding on dynamically created elements? 8 answers I'm currently experimenting with list.js and lodash to produce a dynamic filter functionality on a set of search results. The base of the code is forked from here: http://codepen.io/waynehoover/pen/KBqhF List.Js uses the elements on...

Sort array of objects into Top N using lodash with n+1 as “others”

javascript,arrays,json,angularjs,lodash
Assuming I have this data structure, Example input : [ {name: "a", val:1}, {name: "b", val:2}, {name: "c", val:3}, {name: "d", val:4}, {name: "e", val:5}, {name: "f", val:1}, {name: "g", val:2}, {name: "h", val:1}, ] I want to output 2 arrays : The first is the val attribute from the...

Lodash equals function

javascript,functional-programming,underscore.js,lodash
I need to make several operations with given map: var keys = { a: 1, b: 2, c: 1, d: 2, e: 2 } _.findKey(keys, function(value) { return value === 2; }); // "b" _.omit(keys, function(value) { return value === 2; }); // {a: 1, c: 1} I want to...

Get values of object using lodash

javascript,object,lodash
I've to use lodash for get the values of this object: http://pastebin.com/raw.php?i=U1Z8tzY0 As you can see, I have one big object. I need to get all the autonomias names with the activo property set to true". I've tried to use a lot of functions without result. I'm stuck. And I...

Wrap the function into another function

javascript,functional-programming,lodash
I have the code that sorts an array of objects by the object property using lodash. It’s pretty simple: _.sortBy(data.cycles, "id"); However, I discovered that data.cycles[].id might be a string, so I have to convert each property to number before passing it to _.sortBy. Is there any elegant way of...

Javascript - Base class method not available in derived class when extending using lodAsh

javascript,ecmascript-6,lodash
I have a base class : class Base { constructor() { this.name = "base_class" } getBaseName() { return "base" } } and a Derived class var _ = require('lodash'); class Derived { constructor() { this.name = "derived" } getDerivedName() { return "derived" } } _.extend(Derived.prototype, Base) I was expecting to...

Array manipulation - lodash or underscore js

node.js,underscore.js,lodash
I have a requirement to change the format of an array in lodash or underscore: [ { name: "john", type: "facebook" }, { name: "Mike", type: "facebook" }, { name: "Jacob", type: "twitter" }, { name: "Nancy", type: "twitter" }, { name: "Antony", type: "facebook" }, { name: "Viki", type:...

Karma testing lodash Factory

angularjs,jasmine,karma-runner,karma-jasmine,lodash
i have created a factory for the lodash library in my angular app like so: angular.module('lodash',[]).service('_', function(){ var _ = window._; // i am delete the _ property on the window // so that i m enforced to dependency inject // lodash each time i want to use it //...

Join nested array

javascript,arrays,lodash
I have a result from Q.all() which is something like this - promise = [Arr1,Arr2,Arr3....] Each Arr can be either null or an array of plain JS objects. I want to join all these arrays to one big array; I can loop over and use array concat method to join...

Need help using lodash to reform an array with new structure

javascript,arrays,grouping,lodash
I have this sample data that is returned from an API that I am trying to reform into an array with a sub-array of grouped objects. The raw data from the API looks like this: [ { "InsightId": 314, "Classification": "Advantage", "AttributeId": 14958, "InsightAttribute": "Implementation speed", "AttributeType": "Product Criterion" },...

Generate all possible heads up matchups from array

javascript,node.js,underscore.js,lodash
I am trying to find the performant way to create match-ups for players in an array and return all possible match-ups for all players in a multidimensional array without duplicating any match-ups. Here is my example: // input var players = [ {player: 'sam' }, {player: 'bob' }, {player: 'tim'...

_.debounce doesnt work as expected

javascript,underscore.js,lodash
I want to use lodash debounce() function. Here is the simplest example. var update_from = function (name) { console.log(name); }; $( document ).ready(function() { _.debounce(update_from, 1500)("first"); _.debounce(update_from, 1500)('second'); _.debounce(update_from, 1500)("third"); }); I expect only "third" to be printed into console. But all three are printed. What am I doing wrong...

Merge two object arrays for Chart

javascript,arrays,backbone.js,lodash
I've two arrays which I'm going to merge and then load in chart. range = date array generated from moment.js, there is date of every day in example one month or specific date range with one another attribute count: "0" data = fetched data from database through backbone Now I...

Is there a more concise way to remove an entry from an array with lodash?

javascript,lodash
Below are several stabs at removing 3 from the array [8,2,3,4] using lodash. The elegant syntax for removing an object from an array of objects makes me wonder if I just haven't figured out the right approach here. > _.remove([8,2,3,4], 3) [] > x = [8,2,3,4] [8, 2, 3, 4]...

Lodash - How to get multiple results

javascript,lodash
I am using lodash. I like it. I have a users array which looks like this: var users = [{ 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'pebbles', 'age': 1, 'active': true }]; Here's how I'm finding the first user...

LoDash _.has for multiple keys

javascript,arrays,lodash
Is there a method or a chain of methods to check if an array of keys exists in an object available in lodash, rather than using the following? var params = {...} var isCompleteForm = true; var requiredKeys = ['firstname', 'lastname', 'email'] for (var i in requiredKeys) { if (_.has(params,...

Of a list of properties, check which property an object has? Object can only have one of the properties

javascript,underscore.js,lodash
An object can have either property a, b, c, or d. What’s the best way find out which one it has? var input = { name: 'Bob', a: 1 } Expected output: a I was previously using: _.keys(_.pick(input, 'a', 'b', 'c', 'd'))[0] But was wondering if there was a better...

Lodash Map with mulitvariable function

javascript,lodash
Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following...

Combine nested arrays into one?

javascript,arrays,underscore.js,lodash
Let's say I have an array of objects that look similar to this: [ { id: ..., name: "...", users: [1, 2, 3] }, ... ] Is there a way that I can easily merge the .users array of each object into one array?...

javascript - Picking and Merging arrays

javascript,node.js,mongodb,lodash
So I have a data set that looks like this: [ { ProductID: 1, ProductName: 'MyProduct', Description: '.. some text here ..', UnwantedData: 'garbage here' }, { ProductID: 2, ProductName: 'MyOtherProduct', Description: '.. some text here ..', UnwantedData: 'garbage herAe', GarbageField: '.. lorem ipsum ..' } ] I also have...

Turn object into array, add object as new element

javascript,functional-programming,underscore.js,lodash
Trying to transform an object of objects: var items: { item_a: { state: 'item_a status' }, item_b: { state: 'item_b status' } }; into an array of objects, whilst adding a new array element to the object (the object key): var items = [{ name: 'item_a', state: 'item_a status' },...

Nested Category Search using underscore js

arrays,json,underscore.js,lodash
This is how my data object would look like http://jsfiddle.net/303tpLtz/1 As you may see here there are categories inside categories which must be considered when the search is done So the problem is I can find the top level names of the categories using _.findWhere(result.response.categories, {name: 'Arts & Entertainment'}) But...

how can i retrieve specific fields from object in javascript?

javascript,elasticsearch,lodash
I want to retrieve a part of an javascript objet. The final object sould have all the hits.hits._source i tried different things with lodash or underscore but i did not get it My inital object is { "took": 7, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 },...

Lodash filtering to return object rather than array with 1 length

javascript,arrays,object,lodash
I'm using this code to filter an array: var filteredValues = _.filter(arrayOfObjects, function(obj) { return obj.id === id; }); Here's how I'm trying to get the first result: console.log('id', filteredValues[0].id); I know how to use chaining but I forgot which lodash function I can use so that the first object...

Get the object in an array of object with the key

javascript,node.js,lodash
So I have an array of objects and I want to get the object with the key "Z". Obviously I can just loop through the array and check each key one by one and grab the one which matches, but I was thinking that there is probably a better way...

String manipulation using lodash chaining

javascript,lodash
I want to change the string "Showing 8,868 research papers in XXX Journal; published between 2000-01-01 and 2015-06-31" to: New research papers in XXX Journal; published from 2001-01-01 onward I came up with the following code that uses lodash: var desc = _.chain($('.description').text()) .thru(function (text) { return text.replace(/\s+/g, ' ')...

Immutable _.assign (assign with clone) from lodash underscore or other library?

javascript,underscore.js,lodash
Is there an alternative method available in lodash, underscore or other library that almost behaves the same way, except that it returns a new object instead of mutating the first argument?. var o = { 'user': 'barney' } var result = method(o, { 'age': 40 }, { 'user': 'fred' })...

In lodash.js, will it cache the result for `.value()` method?

javascript,coffeescript,underscore.js,lazy-evaluation,lodash
For example, I have codes (coffeescript) like this: sortedLatLng = _(w) .sortBy (x) -> x.time .map (x) -> [x.longitude,x.latitude] .uniq((x)-> x[0].toFixed(3) + "," + x[1].toFixed(3)) # keep three decimal to merge nearby points console.log(sortedLatLng.value()) myFunction1(sortedLatLng.value()) myFunction2(sortedLatLng.value()) console.log(sortedLatLng.reverse().value()) This may be chained by other lodash method later. Meanwhile, its value may...

how to integrate a lodash custom build into a project

npm,browserify,lodash,package.json
lodash supports custom builds with only a subset of the functionality / size. Creating a custom build is a breeze with lodash-cli. What's the recommended way to take this custom build and integrate it into the project? (using npm / browserify). Do I create a custom build command that creates...

lodash: filter array of objects with a different array of objects

javascript,arrays,lodash
This question is specific to lodash. Given two arrays of objects, what is the best way to filter one array with the objects of the other array? I have attempted to put forth a scenario below, and the way I have gone about doing this is using two .forEach loops,...

Why/How does a lodash “[iteratee=_.identity] (Function)” in _foreach have a 'mystery' third param?

foreach,underscore.js,lodash
I am getting the hang of lodash.js for the first time today and have discovered that you can access the 'value' 'index' and 'list' within the iterator function. I came across this when using the _.foreach function. For example: _.forEach(oMyArray, function(value, index, list){ ... }) However the API specifies only...

Typescript lodash: How to declare a dictionary to use with _.map?

typescript,lodash,typescript1.4
How to declare a dictionary to use with _.map in lodash? Here is the sample TypeScript program. <reference path="../scripts/typings/lodash/lodash.d.ts" /> interface IQuestionAndOptions { text: string; options: { [key: number]: string }; } function sample() { var question: IQuestionAndOptions = { text: "Are you happy?", options: {} }; question['1'] = "Yes";...

ng-repeat displaying only the last item

javascript,angularjs,lodash
I know this is probably my mistake. I am receiving a JSON object which contains WordPress posts, but when I try to render those posts in the DOM, the only post which is 12 times in the list, is the last item <div ng-repeat="post in posts"> <h2 ng-bind-html="post.title"></h2> <p>{{:: post.date...

Retrieving one object from JSON using Angular factory and lodash

javascript,json,angularjs,lodash
I have a locally stored JSON named "Productos", and using UI-router I pass in a $stateParams which I then use to find that object by its unique ID using the new page's controller and a factory shared between several controllers. Right now my console retrieves the correct id number being...

“Segmentize” collection with lodash

javascript,collections,lodash
I have a collection col1 var col1 = [1, 8, 9, 10, 2, 54, 7]; I have another collection col2 var col2 = [1, 8, 23, 9, 46, 10, 2, 54, 78, 7] ...that I know it contains every element of col1, plus some other elements I want to...

Event binding on underscore/lodash templates

javascript,jquery,lodash,underscore.js-templating
I have an example lodash template inside a jquery plugin as shown below: <div> <% _.forEach(circle, function(circle, idx){%> <a class='circle'> <%- circle.circleName %> </a> <%})%> </div> I would like to add click event handler to the a tag. Currently, I am doing the below after rendering the above template on...

array of objects to object - lodash

javascript,arrays,object,lodash
I have this: [ { list: [ [Object], [Object] ] }, { head: [ [Object], [Object] ] } ] And want to turn it into this: { list: [ [Object], [Object] ], head: [ [Object], [Object] ] } So an array of objects into an object. It would be great...

Remove item from object where key is different for each entry

javascript,lodash
I am storing a list of key value pairs in Javascript where he key is different for each entry: 8f348f-b4d0-66bf-b0cj-a31b9c45c: "Pete" ff5764-7863-6pc9-b72f-195f2h962: "Dave" The key is the connection id of the connected session and the value is the username. I then want to remove an item from the list, being...

Using lodash how I can keep a counter that later could used as a parameter?

javascript,loops,refactoring,lodash
here I have a typical for loop, where i is pass as a parameter later .splice() My question is: How I can refactor this with lodash? for(var i =0; i< scope.liveBalls.length;i++){ if(scope.liveBalls[i].bat === scope.ball.bat){ scope.splicedBalls.push(scope.liveBalls.splice(i,1)); } } ...

Create two arrays from a collection of object property and values with lodash

javascript,arrays,javascript-objects,lodash
I have an array that contains objects, like this: [{ "first" : 1 }, { "second" : 2 }, { "third" : 3 }] I want to turn this into two arrays, with indexes matching based on these values, such as: ["first","second","third"] [1,2,3] I can iterate through this and get...

How to Re-format this JSON using Lodash / JavaScript?

javascript,json,lodash
I need to reformat the following JSON data [ { "name": "Hello", "value": 1 }, { "name": "Hello", "value": 11 }, { "name": "Bye", "value": 2 }, { "name": "Bye", "value": 22 } ] to this: [ { "Hello": 1, "Bye": 2 }, { "Hello": 11, "Bye": 22 }, ]...

lodash property search in array and in nested child arrays

javascript,underscore.js,lodash
I have this array: [ { id: 1, name: 'test 1', children: [] }, { id: 2, name: 'test 2', children: [ { id: 4, name: 'test 4' } ] }, { id: 3, name: 'test 3', children: [] } ] How can I filter by the id property in...

LoDash - How to push one collections values into another via common key

javascript,arrays,multidimensional-array,lodash
I have two collections. var a = [ {unique_id: "001", state: "CO"}, {unique_id: "001", state: "TX"}, {unique_id: "001", state: "CC"}, {unique_id: "002", state: "CC"}, {unique_id: "002", state: "NY"} ] And var b = [ {unique_id: "001", states:[]}, {unique_id: "002", states:[]} ] And I want to get: var b = [...

How to make a selectAll checkbox and triggering every function of ng-click on every checkbox?

javascript,angularjs,checkbox,underscore.js,lodash
I have some code that when you click a checkbox, it will perform ng-click. Here is the JS of it. $scope.selectTitle = function(evt, selected){ evt.stopPropagation(); var filtered = _.findWhere($scope.selectedTitles, {id: selected.id}); var index = _.indexOf($scope.selectedTitles, selected); if(selected === filtered){ $scope.selectedTitles.splice(index, 1) } else{ $scope.selectedTitles.push(selected); } console.log('titles', $scope.selectedTitles, 'filtered', filtered, 'index',...

How to not separate on dash/hyphen when using lodash _.words?

javascript,arrays,regex,lodash,words
I am using lodash to split up usernames that are fed to me in a string with some sort of arbitrary separator. I would like to use _.words() to split strings up into words, except for hyphens, as some of the user names contain hyphens. Example: _.words(['user1,user2,user3-adm'], RegExp) I want...

Javascript compare objects having functions using lodash isEqual

javascript,lodash
how to compare two objects for equality if they have functions? lodash's isEqual works really well until functions are thrown in: _.isEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // -> true _.isEqual({ a: 1, b: 2, c: function () { return 1; } }, {...

Why wouldn't lodash 'some' function work as expected?

javascript,sails.js,lodash
I'm trying to use lodash 2.4.1 in order to know if there's at least one element within an array with true as its value. So I decided to use lodash some or any function. This is what my code looks like: if ( _.some([lineup.reachesMaxForeignPlayers(), lineup.reachesBudgetLimit()], true) ) { response.send(400, "La...

Moving a deep-set member of a multidimensional array tree - using lodash or underscore

javascript,multidimensional-array,underscore.js,lodash
I want to move a deep set member of a tree using lodash or equivalent code. Example Tree [ { id: 32, name: 'unique name', children: [] }, { id: 43, name: 'unique name', children: [] }, { id: 55, name: 'unique name', children: [ { id: 31, name: 'unique...

Lodash remove from string array

javascript,lodash
I have an array of string and want to instantly remove some of them. But it doesn't work var list = ['a', 'b', 'c', 'd'] _.remove(list, 'b'); console.log(list); // 'b' still there I guess it happened because _.remove function accept string as second argument and considers that is property name....

How can I remove an item from an array using either javascript or lodash

javascript,angularjs,lodash
My object is below. I am using this in angular and have lodash injected into it. I want to remove the 2nd item using choice2 as what I would pass to match. $scope.choices = [{ id: 'choice1' }, { id: 'choice2' }, { id: 'choice3' ...

How to I set a custom escape RegExp in a lodash template?

javascript,lodash
Here's what I'm trying: _.template("Hello ___name___",{escape:/___(.*?)___/g})({name:"Steve"}) The output I would expect is: Hello Steve But instead I get: Uncaught TypeError: _.template(...) is not a function(anonymous function) Which makes sense because this: _.template("Hello ___name___",{escape:/___(.*?)___/g}) Gives me back the string Hello ___name___ instead of a template function. Are the docs wrong or...

LoDash - DeepFlatten array of objects

javascript,collections,lodash,flatten
I have the following collection. Each object may have a children array of objects, which may have a children array of objects and so on... [ { "name": "John", "age": 24, "children": [ { "name": "Jack", "age": 53, "children": [ { "name": "Jenny", "age": 88 } ] } ] },...

How to get only objects that have a certain atribute inside an array in a Json file using lodash?

javascript,lodash
Codepen: http://codepen.io/giorgiomartini/pen/jEvaxZ I have this Api: http://private-5d90c-kevinhiller.apiary-mock.com/angular_challenge/horror_movies which as this structure like this: As you can see there is an offers array, which has a provider_id, I just want to get the movies that are in provider 2 for example. { "id": 140524, "title": "Dracula Untold", "poster": "https://images.justwatch.com/poster/298962/s332", "full_path": "https://www.justwatch.com/us/movie/dracula-year-zero",...

What is clojure.core equivalent of lodash _.pluck

javascript,clojure,lodash
Lodash _.pluck does this var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 } ]; _.pluck(users, 'user'); // → ['barney', 'fred'] Good thing about it is it can also go deep like this: var users = [ { 'user': {name: 'barney'}, 'age': 36 },...

lodash sortBy then groupBy, is order maintained?

javascript,arrays,sorting,lodash
I'm having trouble figuring out from the lodash documentation if my assumption about sorting and grouping is correct. If I use sortBy, then use groupBy, do the arrays produced by groupBy maintain the sort order of items? For example, say I have the following array: var testArray = [[5,6],[1,3],[5,4],[5,1]] And...

Reorder an array around an index

javascript,arrays,underscore.js,lodash
My issue is very simple to explain, but figuring out the most efficient way of doing it is proving difficult. I am trying to reorder an array starting at a particular index in the array. What I have: var array = [1,2,3,4,5]; What I want: array = [3,4,5,1,2]; What I've...

How does the _.invoke method work in Lodash?

javascript,underscore.js,lodash
Background From the documentation about the invoke method, I read: Invokes the method named by methodName on each element in collection, returning an array of the results of each invoked method Thus, I assumed that the following code would be synonymous, but this is not the case: _.map(items, function(item) {...

javascript: always pass the nth argument in a function as fixed value by default

javascript,lodash
the function takes 3 parameters like function p(x,y,z){ console.log(arguments); } so when we call it like p(12,21,32) a fourth argument should pass as say 56 so effectively the call should be p(12,21,32,56) How to do this? Condition We cannot change the function definition. I need to partially bind the fourth...

How to build out this complex Array based on this Simple Object

javascript,arrays,object,lodash
http://jsfiddle.net/leongaban/tuhgns3q/ My simple object: { portfolio: "AAPL", t1_tag1: "1111", t2_tag1: "2222", t3_tag1: "3333", ticker1: "AA", ticker2: "GOOG", ticker3: "AAPL" } The desired end result below. Array with Objects containing Array of Objects: [ 0:Object { tags: [ 0:Object { t1_tag1: "1111" } ] ticker: ticker1 }, 1:Object { tags: [...

how to sort an array of objects using a related property from objects in second array

javascript,underscore.js,lodash
There are many questions regarding sorting with JavaScript but I didn't find anything that addresses this case so I don't believe this is a duplicate. I'm getting data like this back from an api: //items array var items = [{id:1, name:'bill'}, {id:2, name:'sam'}, {id:3, name: mary}, {id:4, name:'jane'}] //sort order...

Proper lodash method

javascript,lodash
I have an objected named slip, this object contains a property active which the attr is '1', when the slip object is not selected the property active has an attr '0'. I have a function that I need to apply only when the property active has the attr '0'. I...

Find number of occurences of string elements in an Array using lodash or underscore js

javascript,underscore.js,lodash
I have an array in the following format: var array = [ { id: '555weibo' }, { id: '578weibo' }, { id: '111facebook' }, { id: '123facebook' }, { id: '145facebookpage' }, { id: '145facebookpage' }, { id: '766facebook' }, { id: '242facebook' }, { id: '432twitter' }, { id:...

any lodash functions for removing array that is matching from main array

javascript,arrays,json,lodash
I have two array available, selected which is having some values. I am having another array named finalAvailable in which I want all those from the available array at the same time also to remove those which are present in selected array. An example is shown below var available =...

using lodash to compare arrays

javascript,arrays,lodash
I know I can do this using loops but I am trying to find an elegant way of doing this: I have two arrays: var array1 = [['a', 'b'], ['b', 'c']]; var array2 = [['b', 'c'], ['a', 'b']]; how can I use lodash to confirm that these two are the...

How to split javascript array of object with specific condition using lodash/underscorejs

javascript,arrays,object,underscore.js,lodash
I have array of objects like this: var data = [ { type : "parent", name : "A" }, { type : "child", name : "1" }, { type : "child", name : "2" }, { type : "parent", name : "B" }, { type : "child", name : "3"...

lodash 'includes' not working

javascript,lodash
I tried to use this function, but it's not defined (jsfiddle). console.log(_.include([1, 2, 3], 1)); console.log(_.includes([1, 2, 3], 1)); also I saw that 'include;' without 's' work well. they have mistake in the docs? or I missed something? thanks!...

Any way to use immutable.js with lodash?

javascript,reactjs,immutability,lodash,immutable.js
I'm using immutable.js with my flux application. It is very useful and gives performance boost. But what actually makes me sad is the fact that I can't use lodash together with it. Lodash provides great API with ton of useful functions, so I wonder maybe there is a way to...

Nested _.max() with lodash

javascript,arrays,lodash
I am trying to get max and min values of arrays values inside objects array which looks like this: [ { id: 1, enabled: false, layer: 'Mood', color: '#f16c63', points: [ {date: '2013-01-02', value: 20}, {date: '2013-02-02', value: 15}, {date: '2013-03-12', value: 24}, {date: '2013-03-23', value: 18}, {date: '2013-03-24', value:...

merge array object together - lodash

javascript,arrays,merge,lodash
So I have an array of items like this: items = [ { amount: 2, name: 'bike' }, { amount: 1, name: 'boat' }, { amount: 3, name: 'bike' } ] Now, I would like to merge this array so that there would be no duplicates of bike and still...

Use .map to turn quantity into percentages

javascript,underscore.js,lodash
I'd like to use Javascript's lodash to turn this object of arrays into percentages. Here is the object: gender = { female: [14, 33, 28, 49], male: [33, 50, 42, 61] } I would like the above object to be genderPercent = { female: [0.2978, 0.3975, ..., ...], male: [0.7021,...