[Vuejs]-Trying to filter an array using VueJS and showing only the results

1👍

You can use a computed property if you wish to leave the cars array without modifications and filter it in-memory.

<div v-for="car in filteredCars"</div>
...
<script>
...
export default {
...
  data () {
    return {
      cars: [],
...
computed: {
  filteredCars () {
    // a simple filter by indexOf, for demonstrating purposes only
    return this.cars.filter(x => x.description.indexOf(this.search) !== -1)
  }
}

0👍

You can do that using the sort method in javascript es6

const activities = [
  { model: 'Toyota', date: new Date('2019-06-28'), year: 2009},
  { model: 'Benz', date: new Date('2019-06-10'), year: 2009 },
  { model: 'Ford', date: new Date('2019-06-22'), year: 2009 }
]

const sortedActivities = activities.sort((a, b) => b.date - a.date)

console.log(sortedActivities)

0👍

You can filter it easily by using lodash

<script>
import _ from 'lodash'

...
export default {
...
    data () {
        return {
            cars: [],
        }
    }
...
    methods: {   
        onFilter: function(filterKey = 'year') {
            this.cars = _.orderBy(
                this.cars, (car) => {
                    return car[year]
                },
                'desc'
            )
        }
    }
}

Now all you have to do is to bind this onFilter() method with your button event

Leave a comment