Sort a table in vue js

I have a problem sorting my table in vue.js. I would like to have my table sorting the campaign with the highest spend at the top and then descending. I have the following code:

<template>
    <div class="row">
        <h1> Campaign performance </h1>
        <table class="table table-sortable">
            <thead>
                <tr>
                    <th scope="col">Client</th>
                    <th scope="col">Mediachannel</th>
                    <th scope="col">Campaign</th>
                    <th scope="col">Spend</th>
                </tr>
            </thead>
        <tbody>
            <tr v-for="(campaign, name) in campaignPerformance" :key="campaign.campaignID">
                 <td>{{campaign.client}}</td>
                 <td>{{campaign.mediaChannel}}</td>
                 <td>{{campaign.campaign}}</td>
                 <td>{{Intl.NumberFormat('da-DK').format(Math.round(campaign.spend))}}</td>
            </tr>
        </tbody>
        </table>
</div></template>
<script>
export default {
 data() {
  return {
  };
 },
props['campaignPerformance']
components: { },
methods: {
},
created () { },
};
</script>

I have tried adding different functions in the method. However, all methods I have tried has failed. If anyone can help sorting this table, it would be greatly appreciated!!!

Upvotes: 0

Views: 75

Answers (2)

lamboktulus1379
lamboktulus1379

Reputation: 370

Try this...

let arr = [
  {
    client: "aa",
     mediaChannel: "media",
    campaign: "Campaign",
    spend: 100
  },
  {
    client: "bb",
     mediaChannel: "media1",
    campaign: "Campaign2",
    spend: 200
  }
  
];

let newarr = arr.sort((a, b) => {
  //return a.spend - b.spend; // Ascending
 return b.spend - a.spend;  //Descending
});

console.log(newarr);

Upvotes: 1

User 28
User 28

Reputation: 5158

Try this:

<template>
  <div class="row">
    <h1> Campaign performance </h1>
    <table class="table table-sortable">
      <thead>
        <tr>
          <th scope="col">Client</th>
          <th scope="col">Mediachannel</th>
          <th scope="col">Campaign</th>
          <th scope="col">Spend</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="campaign in sortedCampaignPerformance" :key="campaign.campaignID">
          <td>{{campaign.client}}</td>
          <td>{{campaign.mediaChannel}}</td>
          <td>{{campaign.campaign}}</td>
          <td>{{Intl.NumberFormat('da-DK').format(Math.round(campaign.spend))}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  export default {
    props['campaignPerformance']
    computed: {
      sortedCampaignPerformance() {
        return this.campaignPerformance.sort((a, b) => b.spend - a.spend)
      }
    }
  };
</script>

Upvotes: 2

Related Questions