sort response data based on date in vue

Is there a way to sort response data by date in vue2? Specifically, how can we filter the data by month, year, or week when a corresponding button is clicked?

Here's an example of the response data I received: [ { "date": "2017-02-05", "views": 1, "readMore": 1 }, { "date": "2018-03-15", "views": 1, "readMore": 1 }, { "date": "2018-01-27", "views": 2, "readMore": 2 } ].

Thank you in advance for any help.

computed: {
  DateWise: function () {
    if(this.duration === 'year'){ 
      return this.data.filter(item => item.date.includes(new Date().getFullYear()));
    }
    else if(this.duration === 'month'){ 
      return this.data.filter(item => item.date.includes(new Date().getMonth()+1));
    }
  }
},

Answer №1

It's important to note that JSON does not natively handle dates, so a common practice is to convert date strings into date objects upon deserialization. Once you have your source data stored, you can then create computed properties for your filtered arrays.

Take a look at this working example for reference.

Below is the code snippet for the filtered property...

displayDates(){
    var now = new Date(Date.now());
    switch(vueStore.currView){
    case 'all': return vueStore.allDates;
    case 'month' : return vueStore.allDates.filter(
        line => line.date > new Date(now.getFullYear(), now.getMonth(), 0)
    );
    case 'year' : return vueStore.allDates.filter(
        line => line.date > new Date(now.getFullYear(), 0, 0)
    )
  }
}

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

Using Vue's interpolation within the src attribute of my image tag: "{{ image }}"

I am attempting to pass an image url dynamically to my Vue application, but it doesn't seem to be working. I'm starting to question if this is even achievable in Vue / Vuetify. Please confirm if this functionality is possible. <v-img class=& ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

Nuxt.js encountered an unexpected keyword 'export' causing a parsing error

Within my index.js file in the 'store' section, I am encountering the following code: import Vuex from 'vuex' // import axios from 'axios' const createStore = () => { return new Vuex.Store({ state: { loadedPost ...

How should an object be properly passed as a prop using vue router?

In my application, I have a PreviewProduct component that emits a product object to the App.vue file when clicked. My next goal is to pass this product object to the DetailedProduct component using the following method: handleProductClicked(product) { ...

I am unable to access the specified file through the direct URL on the VueJS app with Vue Router that is hosted on Ampl

Today, I encountered a persistent issue with my VueJS app hosted on amplify. Everything is running smoothly, except for one thing. I need to provide direct access to a file (specifically to register an Apple merchant ID with stripe). I attempted to creat ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

Developing components through JavaScript

I am attempting to use JavaScript to create an element in my HTML using createElement, but there seems to be an issue in my code. HTML <button class="test_button">I am a test</button> <div class="test"></div> ...

I am seeking a solution to this error that occurs whenever I attempt to call a function using a button

Issue " _ctx.hello is not a function TypeError: _ctx.hello is not a function at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/di ...

Vue warning: The v-on handler encountered an error (Promise/async) with the message "TypeError: Cannot read property 'get' of undefined" while using Vue test utils

I want to simulate an axios put request in nuxt.js using the following code: The method in the component (Composition API approach): const doSomething = async (): Promise<void> => { const token = $cookies.get("token"); const header ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...

Identifying separator when v-carousel is selected

How can I detect when a delimiter is clicked on a v-carousel? https://i.stack.imgur.com/9M1XL.jpg ...

Replicate form element

I am having trouble duplicating form items Greetings to all. I have a form and I'm looking to add a button that allows users to duplicate fields each time they click on it. Here is my form: <v-layout v-for="(phone, index) in people.phones" :key=" ...

Modifying tag classes dynamically with JavaScript

I am working on creating a list of projects where the user can select one as the default project for future use in other processes. The issue I am facing is that each project in the list has a unique id and by default, they all have the RegularIcon class ...

Error: serialport in node_modules throwing unexpected token SyntaxError

I have been attempting to run the vue-electron app, but I keep encountering this error. App threw an error during load C:\newFolder02\pos4-desktop\node_modules\@serialport\stream\lib\index.js:103 const settings = ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

Discover the method to retrieve the month name from an HTML Date input value

Here we have a date input field <input id="customer-date" name="customer-date" type="date" required> Accompanied by this script const customerDate = document.getElementById('customer-date').value; const dateHandler = document.getElementB ...