Using Lodash to filter a deeply nested array by passing in a custom function

Is there a way to extract only the items in the nested arrays that meet a specific criteria or expression?

I've looked at the following links, but the solutions provided do not seem to work with _.filter:

Find object by match property in nested array

lodash property search in array and in nested child arrays

Lodash - Search Nested Array and Return Object

Let me provide more context. I have data structured like this: How can I retrieve the items inside the "listEvents" array for all objects that match a certain criteria?

[
  {
    "ModalidadeId": 1,
    "Nome": "SOCCER",
    "Ordem": "09",
    "IconeId": "",
    "listEvents": [
      {
        "EI": 2960542,
        "No": "SÃO PAULO SP X ATLÉTICO LINENSE-SP",
        "St": 1,
        "Ini": "2017-09-30T10:00:00",
        "MI": 1,
        "CI": 251,
        "TI": 4993,
        "StAV": 0,
        "De": false,
        "Ics": [
          "p22678",
          "p22684"
        ],
        "Ic": "",
        "Tas": [],
        "show": true,
        "IniFormatada": "30/09/2017 às 10:00:00",
        "MN": "FUTEBOL"
      },
      ...
    ]
  },
  {
    "ModalidadeId": 2,
    "Nome": "TENIS",
    "Ordem": "09",
    "IconeId": "",
    "listEvents": [
      {
        "EI": 2960542,
        "No": "SÃO PAULO SP X ATLÉTICO LINENSE-SP",
        "St": 1,
        "Ini": "2017-09-30T10:00:00",
        "MI": 1,
        "CI": 251,
        "TI": 4993,
        "StAV": 0,
        "De": false,
        "Ics": [
          "p22678",
          "p22684"
        ],
        "Ic": "",
        "Tas": [],
        "show": true,
        "IniFormatada": "30/09/2017 às 10:00:00",
        "MN": "FUTEBOL"
      },
      ...
    ]
  }
]

This is the code snippet I've attempted, but it doesn't seem to be functioning properly.

_.filter($scope.listModalities, _.flow(
            _.property('listEvents'),
            _.partialRight(_.filter, function (o) {
              var eventDate = new Date(o.Ini);
              eventDate.setHours(eventDate.getHours() - 24);
              var now = new Date();
              return o.De == true || eventDate < now;
            })
          ));

Answer №1

To optimize your code, consider mapping to listEvents and then flattening the array in order to eliminate one iteration loop and achieve the desired results:

var now = new Date();
var listEvents = _.chain(input).map((o) => o.listEvents).flatten().filter((o)=> {
  if(o.De === true) return true;
  var eventDate = new Date(o.Ini);
  eventDate.setHours(eventDate.getHours() - 24);
  return eventDate < now;
}).value();

now = null;

I have also optimized the equality check o.De === true so that the function terminates early if the condition is met. Furthermore, I moved the declaration of now outside of the loop for efficiency.

Take a look at this pen for reference.

If you prefer an alternative, here's how the code would appear in ES5:

var now = new Date();
var listEvents = _.chain(input).map(function (o) {
  return o.listEvents;
}).flatten().filter(function (o) {
  if (o.De === true) return true;
  var eventDate = new Date(o.Ini);
  eventDate.setHours(eventDate.getHours() - 24);
  return eventDate < now;
}).value();

Here is another pen demonstrating this method.

Additionally, for further optimization suggested in the comments, you can utilize flatMap to streamline the process:

var now = new Date();
var listEvents = _.chain(input).flatMap('listEvents').filter(function (o) {
  if (o.De === true) return true;
  var eventDate = new Date(o.Ini);
  eventDate.setHours(eventDate.getHours() - 24);
  return eventDate < now;
}).value();

console.log(listEvents);

Check out this pen for a demonstration.

Answer №2

Perhaps you could experiment with using vanilla JavaScript

let eventList = []

data.forEach((item) => {
item.events.forEach((event) => {
     let eventDate = new Date(event.start);
     eventDate.setHours(eventDate.getHours() - 24);
     let now = new Date();
     if(event.done == true || eventDate < now){
        eventList.push(event);
     }
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use jQuery/JS to automatically format currency input as it is typed, adding a 1000 separator and ensuring

I'm working on a text input field that needs to format the value as it is being typed, with restrictions of 2 decimal places and 1000 separators. This field should only allow for digits to be entered. Specifically, this input is meant for users to ent ...

Tips for adding one document to two separate collections using JavaScript and MongoJS

Having trouble inserting data into two separate tables using javascript and mongojs. While I was able to successfully insert into a single collection by following the npm mongojs documentation, I couldn't find a solution for multiple collections on th ...

C implementation of a pseudo-generic dynamic array list that crashes at the end while attempting to delete resources

In my C programming, I have developed a pseudo-generic dynamic array for primitive types using enum constants like INT, LONG_INT, DECIMAL, and CHAR. The main structure list includes a member called _assets, which is a void pointer to provide an abstraction ...

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

Assigning state values in React based on an array in ES6

In my React application, I have a state variable defined as: this.state = { formStatus : { approved : true, rejected : true, pending : true } } Additionally, there is a dynamic array called appliedFilters which can contai ...

How to Pass an Array of Structs as a Return Value in C

I've been struggling to pass a struct array from a function. I've searched extensively but haven't found a solution yet. Below is the code I've been working on. struct menuItemType { int itemNo; string menuItem; double pric ...

What is the best way to customize the spacing of grid lines in chartist.js?

I am struggling with chartist.js. I want to increase the spacing between y-axis gridlines by 40px. (Currently set at 36px) I have tried looking for examples, but haven't found any. .ct-grids line { stroke: #fff; opacity: .05; stroke-dasharray: ...

Load images easily using jQuery

I am experiencing a small problem. I am attempting to display an image, but it doesn't seem to be correct. Although I am able to retrieve the data of the image, my goal is just to display it instead. What could be causing this issue? var imageUrl = ...

What steps can I take to create a bar that animates in just 1 second using HTML, CSS, and JavaScript?

I'm currently working on a custom progress bar in Javascript that updates every second and then resets. I attempted to use setInterval() to change the value, but I couldn't get it to work. Any assistance would be greatly appreciated, thank you! ...

What is the optimal method for organizing JavaScript and CSS files within my Play2 application?

Trying to figure out the best way to organize my js and css files for my app. If I examine the structure of a play2 app: app → Source code for the application └ assets → Compiled asset sources └ stylesheets ...

How to handle the Conflict in jest snapshot testing when the source is deleted and target is modified?

While working with Bitbucket, I encountered an error when trying to merge from the develop branch to master: The file is currently in a conflicted state and needs to be resolved manually before the pull request can be merged. If I change the conflicting ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

strtok vanishing after returning -1

Currently, I am working on a code that involves inserting strings into arrays and everything is functioning smoothly. However, I am facing an issue where I need the code to stop reading the strings when it encounters a ## in the file. The loop runs through ...

Is there a way to maintain the checked status of the checkboxes after a page refresh?

Is there a way to keep the checkboxes checked even after the page is refreshed in this code snippet? Any code sample or explanation on how to achieve this would be highly appreciated. The complete project code can be found here: https://github.com/Orelso/P ...

Using Three.js to ensure that child object3d expands within the boundaries of its parent object

In this scenario, I have 2 Object3Ds with one nested inside the other: var obj1 = new THREE.Object3D(); var obj2 = new THREE.Object3D(); obj1.add(obj2); Assuming obj1 is AxB units wide, how can I instruct obj2 to match that size? Essentially, how can I m ...

Distinguishing between a regular JavaScript variable and one annotated with a dollar sign

Many responses have addressed the question of using a dollar sign in JavaScript variables. In essence, the dollar sign functions as an identifier in JavaScript variables. However, I am curious if there are other distinctions between regular variables and ...

Set the state of a nested array object within SectionList data using the index

I'm currently working on populating a SectionList with data retrieved from a SQLite database. Here is where I begin: constructor(props) { super(props); this.state = { loading: true, sectionListData: [ { ...

I am on the lookout for a spell-checking tool that can seamlessly integrate with both Django and Python 2.7

Is there a way to detect spelling errors in real-time as the user types, with support for multiple languages? Your help would be greatly appreciated. Thanks! ...

The POST response I received was garbled and corrupted

Operating under the name DownloadZipFile, my service compiles data and constructs a Zip file for easy downloading. This particular service provides a response that contains the stream leading to the file. A Glimpse of the Service: [HttpPost] public Actio ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...