What is the best way to merge several filters into one filter function in order to retrieve data for a specific month?

A smarter approach to improve efficiency and reduce time complexity (n^3) while retrieving all variables.

  • getrewarddata represents an object
  • d1, d2, d3... are individual variables

//Object contains various rewards for different months
const getrewarddata = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

//Split the array based on specific month variable
let d3 = getrewarddata.filter((data) => data.month === 3);

let d2 = getrewarddata.filter((data) => data.month === 2);

let d1 = getrewarddata.filter((data) => data.month === 1);

console.log(d2);
console.log(d3);

Answer №1

A possible solution is to use a grouping method. You can refer to this approach which seems to work well:

//Object has multiple rewards and different month
const getrewarddata = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};


var groupedByMonth = groupBy(getrewarddata, "month");

console.log(groupedByMonth);

Answer №2

To simplify this process, consider creating a function that acts as a helper or wrapper to avoid repeating the same code.

const dataFilter = (month) => getrewarddata.filter((data) => data.month === month);

You can then utilize this helper function like so:

let month3Data = dataFilter(3);
let month2Data = dataFilter(2);
let month1Data = dataFilter(1);

Answer №3

Your code snippet appears to be functioning correctly, but it's not entirely clear what your end goal is. One suggestion would be to create a reusable function that can be called for each variable, which could help reduce the amount of repetitive code you currently have.

const rewardData = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

function filterByMonth(arr, n){
    return arr.filter((data) => data.month === n)
}

let januaryRewards = filterByMonth(rewardData, 1)
let marchRewards = filterByMonth(rewardData, 3)
console.log(januaryRewards)
console.log(marchRewards)

Answer №4

Here is a different approach that involves iterating over the array only once.

let organizedData = getrewarddata.reduce((accumulator, entry) => {
        if (accumulator[entry.month] == undefined) { 
            accumulator[entry.month] = [entry];
        } else {
            accumulator[entry.month].push(entry);
        }
        return accumulator;
    }, {})

With this method, you will obtain an object structured like this:

{
    "1": [
        {
            "month": 1,
            "year": 2021,
            "reward": 6
        }
    ],
    "3": [
        {
            "month": 3,
            "year": 2021,
            "reward": 6
        }
    ],
    "6": [
        {
            "month": 6,
            "year": 2021,
            "reward": 6
        }
    ]
}

You can now access this data in a similar way as a regular object

organizedData[1]
=> [{
        "month": 1,
        "year": 2021,
        "reward": 6
    }]

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

Issues with jQuery show and hide functionality are not performing as expected

A dazzling animation has been created, fading in and out gracefully. With two buttons at hand $('.point li') to reveal distinct contents $("#"+classVal+" .table-cell") Nevertheless, upon clicking $('.point li'), I aspire for its conte ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

Best practice for minimizing JavaScript in the webpack configuration file

Currently, I am following a tutorial on webpack, but it appears that the tutorial is based on an older version of webpack. I am attempting to reduce the size of the .js files, however, every time I execute npm run webpack, I encounter the following error m ...

Mismatch between ng-if and $index causing inconsistency

Is there a way to display a schedule with breaks after every group of matches within a week? For example, is it possible to have an <hr> tag appear after the first five matches in week 1 and then again after five matches in week 2? Currently, my code ...

Define URL parameters within the ngResource framework

My current setup involves utilizing ngResource in my service to retrieve comments for specific news posts within my web application. However, I am facing an issue where the query for comments for a particular news post, article.comments = commentService.q ...

Using Yii2, create a button with an onclick event that executes a JsExpression

I need to submit a form with an array of elements whose number is unknown. class DynamicForm extends Model { /** var string[] */ public elements[]; } In the view where the form submission takes place, I want to include a button that triggers a Ja ...

Retrieve the HTML location of each element stored in a database using JavaScript

I have a scenario where I am fetching elements from a PHP database and my objective is to modify the style of the HTML tags containing them when they are hovered over using JavaScript. However, I am facing an issue where this functionality only works for t ...

PHP child categories causing jQuery menu loading issue

Our custom jQuery menu has been functioning perfectly on our OpenCart store. However, we are facing an issue where the 2nd level child categories are not being displayed. It seems that there is an error in the PHP code for both the modified and original me ...

The method options.domAPI is not a valid function in this context

While attempting to customize global variables using stylus config in Vuetify, I discovered that it is no longer supported. To address this issue, I executed the following command to install the necessary loaders: npm i --save-dev stylus stylus-loader css ...

Accessing Data within PHP Arrays

My configuration array looks like this: $config = array ( 'db' => array( 'db1' => array( 'dbname' => 'mydatabase', 'user' => ...

Having trouble updating the default value in a react-select field

I'm currently utilizing redux-form along with a custom component that integrates react-select. The dropdown I created allows for pre-filled options and the ability to input custom values. I am specifically using the "creatable" component from react-s ...

ES6 / JavaScript - Combining objects based on a particular key

I am attempting to merge an object based on a specific key (where 'field' serves as the key) but I am struggling to find a solution. The images below provide a visual representation of my issue. https://i.sstatic.net/FOAYo.png https://i.sstatic ...

I encountered an error while attempting to capture a screenshot of an element using selenium-webdriver - an UnsupportedOperationError was thrown

I have a code snippet that currently looks like this: var webdriver = require('selenium-webdriver'), until = webdriver.until, By = webdriver.By, fs = require('fs'); var driver = new webdriver.Builder() .forBrowser('chrome' ...

When I try to insert new data into a MongoDB collection during an update operation, the existing data is being overwritten instead

While updating data, I have a requirement to also add new data. Specifically, I need to append data to an existing object in a for loop that stores data in a database. However, when attempting this, the data is being updated instead of added to the current ...

I find it challenging to prevent Array in OCaml from being modified

Here you can find the entire code. I'll share some snippets with you. Currently, I am developing a tic-tac-toe server that operates through telnet. This snippet demonstrates the game board structure: let empty_board = [| [|EMPTY; EMPT ...

Utilize Bootstrap modal to input information into the DataTables library

I am trying to use a bootstrap modal to insert data, but I am encountering an error on the action index. As a result, the button that I added is not functioning correctly. Can someone please review my code to see if there are any mistakes? User Action Con ...

Having trouble bringing in icons from the @mui/icons-material library

An error occurs when attempting to run the code. wait - compiling... error - ../../../../../node_modules/@mui/icons-material/esm/utils/createSvgIcon.js:1:0 Module not found: Can't resolve '@mui/material/utils' null Note: @mui/material pack ...

How can I check if a value inputted into a form is empty in Vue version 2?

I have attempted various methods using alert() and simple if-else statements, as well as referencing the guide available at this link. However, none of these approaches seem to be effective. Can anyone point out what I might be doing incorrectly? Here is ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...