A guide on efficiently organizing and refining an array of objects in Vue

I have been working on filtering and sorting an array of objects in Vue. While I have successfully implemented the filtering functionality, I am now looking to incorporate a sorting feature as well. To achieve this, I have set up a dropdown component through which the selected sorting option is sent via the Event Bus to the component responsible for sorting.

However, my challenge lies in displaying both filter and sort options simultaneously.

Below is the component responsible for rendering the array of objects and handling the filtering/sorting:

<template>
  <div class="cards">
    <CountdownCard
      v-for="(event, index) in filteredItems"
      :key="index"
      :event="event"
    />
  </div>
</template>

<script>
import CountdownCard from '@/components/CountdownCard'
import EventBus from '@/components/EventBus'

export default {
  components: {
    CountdownCard
  },
  data() {
    return {
      events: [
        {
          title: 'Christmas',
          date: 'December 25, 2020',
          emoji: '🎅🏼',
          type: 'holiday',
          year: 2020,
          month: 11,
          day: 21,
          hour: 0,
          minute: 0
        },
        {
          title: 'Spring',
          date: 'March 21, 2020',
          emoji: '💐',
          type: 'season',
          year: 2021,
          month: 2,
          day: 21,
          hour: 0,
          minute: 0
        },
        {
          title: "Tyler's Birthday",
          date: 'September 14, 2020',
          emoji: '🎂',
          type: 'custom',
          year: 2020,
          month: 8,
          day: 14,
          hour: 0,
          minute: 0
        }
      filter: '',
      sort: ''
    }
  },
  mounted() {
    return (
      EventBus.$on('filter-categories', filter => {
        this.filter = filter
      }),
      EventBus.$on('sort-categories', sort => {
        this.sort = sort
      })
    )
  },
  computed: {
    filteredItems: function() {
      // filters at work
      return (
        this.events
          // search filter
          .filter(event => {
            return event.title
              .toLowerCase()
              .includes(this.updateSearch.toLowerCase())
          })
          // category filters
          .filter(event => {
            if (this.filter == '' || this.filter == 'all') {
              return this.events
            } else {
              return event.type == this.filter
            }
          })
      )
    },
    sortedItems: function:{
        // logic for sorting
  }
}
</script>

And here is the component for the dropdown functionality:

<template>
  <div class="dropDownContainer">
    <div class="selection" :class="{ opened: opened }" @click="toggle">
      <span class="selectionText">
        {{ selected.label }}
        <span class="downArrow"></span>
      </span>
    </div>
    <transition name="grow">
      <div class="options" v-if="opened">
        <span
          v-for="(option, index) in choices"
          :key="index"
          @click="makeSelection(option), emitSort(option.name)"
        >
          {{ option.label }}
        </span>
      </div>
    </transition>
  </div>
</template>

<script>
import EventBus from '@/components/EventBus'

export default {
  props: {
    choices: Array,
    menuLabel: String
  },
  data: function() {
    return {
      selected: this.choices[0],
      opened: false,
      sortResult: ''
    }
  },
  methods: {
    toggle: function() {
      this.opened = !this.opened
    },
    makeSelection: function(selected) {
      this.selected = selected
      this.opened = false
    },
    emitSort(option) {
      this.sortResult = option
      EventBus.$emit('sort-categories', this.sortResult)
    }
  }
}
</script>

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

Integrating a spinner into a React component

I am currently working on implementing a loader for my react component. The idea is that when the background image is loading, it should display 'loading', and once it has finished loading, it should display 'loaded' To test the loader ...

"Enhance Your Highchart Experience by Adding Hyperlinks to Every Segment of Your Stacked Bar

I am seeking to assign a specific link to each segment of a stacked 100% bar chart. Check out this demo of a stacked bar chart: http://www.highcharts.com/demo/bar-stacked Here's what I am trying to accomplish: Please visit , input data in the left t ...

When encountering issues with the select element, such as when it is combined with AJAX or Bootstrap,

When attempting to use a foreach loop within the <select><option> ... </option></select> element with jquery + ajax, I encountered an issue where no values were displayed. Although there were no errors when reviewing the console lo ...

Guide on how to programmatically assign a selected value to an answer using Inquirer

Currently, I'm utilizing inquirer to prompt a question to my users via the terminal: var inquirer = require('inquirer'); var question = { name: 'name', message: '', validation: function(){ ... } filter: function( ...

What is the best approach to dynamically enable or disable a button depending on the state of multiple checkboxes in React.js?

Incorporated within a page is a component responsible for displaying multiple checkboxes and toggles. Located at the bottom of this component is a button labeled confirm, designed to save modifications and initiate a backend update request. A new functio ...

Is it possible to determine the duration of a JQuery AJAX call's execution?

Is it possible to measure the duration of a $.getJSON method call using timing code in jQuery/JavaScript? Additionally, is there a method to determine the size of the response Content-Length, measured in kilobytes or megabytes? ...

The canvas animation displays a sequence of previous frames

My challenge lies in rotating an object on the canvas, as all previous frames continue to be displayed. I suspect the issue is related to this particular line of code: setTimeout(this.rotate.bind(this), 1000 / 10); Is there a way to have only the current ...

Incorporating D3's library functions into Rxjs for seamless integration with Observables

I'm really struggling with this concept and could use some guidance. My goal is to monitor when data is fetched, but I seem to have confused the process. Here's what I've tried so far: Using d3.tsv for an ajax request. var test = Rx.Observa ...

Ignore linting errors in the Webpack React Fast Refresh plugin for faster performance

I have integrated the following plugin for Hot Module Replacement (HMR): https://www.npmjs.com/package/@pmmmwh/react-refresh-webpack-plugin. How do I prevent it from blocking the page display due to non-breaking errors, such as linting issues? Here is a ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...

Transforming a JSON object property value from an array into a string using JavaScript

I am facing an issue with an API call I am using, as it is sending objects with a single property that contains an array value (seen in the keys property in the response below). However, I need to work with nested arrays in order to utilize the outputted v ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

Exiting callback function in JavaScript

Is there a way to retrieve the return value from within a node.js/javascript callback function? function get_logs(){ User_Log.findOne({userId:req.user._id}, function(err, userlogs){ if(err) throw err; if(userlogs){ ...

What is the best way to showcase a single item from an array in Vue.JS?

Suppose I have a list of items in Vue.JS data () { return{ items: [ { itemID: 5, itemText: 'foo' }, { itemID: 3, itemText: 'bar' } ] } } Now, if I want to show the item with the itemID of 3 i ...

Set tab navigation widget with a fixed height

I am struggling with setting a fixed height for my tabs widget so that when I add more content, it will display a scrollbar instead of expanding endlessly. I have checked the CSS and JS files but cannot figure it out. It is important for me to contain this ...

Not receiving connections on localhost port 3000

Our team has successfully created a basic Express Node website https://i.stack.imgur.com/5fwmC.png We attempted to run the app using DEBUG=express_example:* npm start https://i.stack.imgur.com/NI5lR.png We also tried running it with node DEBUG=express_ ...

Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes. Below is the HTML code for this component: <div><mat-checkbox [(ngModel)]="pending">Pending</mat-checkbox></div> <div><mat-checkbox [(ngModel ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

A step-by-step guide on connecting an event listener to the search input of Mapbox GL Geocoder in a Vue application

I've encountered a challenge trying to add an event listener to the Mapbox GL Geocoder search input within a Vue application. It appears to be a straightforward task, but I'm facing difficulties. My objective is to implement a functionality simi ...