DEV Community

KevsterDev
KevsterDev

Posted on

VUE3 reverse an array

Let's say we have an array of objects inside db.json file and imagine this scenarios:

  • In Home.vue we want to show only the last 5 jobs added
  • In AllJobs.vue we want to show all jobs but starting with the newest ones
{
  "jobs": [
    {
      "position": "1",
      "department": "test",
      "location": "test",
      "id": 1
    },
    {
      "position": "2",
      "department": "test",
      "location": "test",
      "id": 2
    },
    {
      "position": "4",
      "department": "test",
      "location": "test",
      "id": 4
    },
    {
      "position": "5",
      "department": "test",
      "location": "test",
      "id": 5
    },
    {
      "position": "6",
      "department": "test",
      "location": "test",
      "id": 6
    },
    {
      "position": "7",
      "department": "test",
      "location": "test",
      "id": 7
    }
}
Enter fullscreen mode Exit fullscreen mode

Now it's time to render the array in both Home.vue & AllJobs.vue.

<div v-for="job in jobs" :key="job.id">
    <JobComponent />
</div>
Enter fullscreen mode Exit fullscreen mode

As we said, in Home.vue we want to display only 5 jobs and we can use slice() for this.

<div v-for="job in jobs.slice(0, 5)" :key="job.id">
    <JobComponent />
</div>
Enter fullscreen mode Exit fullscreen mode

Now, we want the jobs in reverse mode, because we want the latest job to be showed first. We are using reverse()

<div v-for="job in jobs.slice(0, 5).reverse()" :key="job.id">
    <JobComponent />
</div>
Enter fullscreen mode Exit fullscreen mode

Next, in AllJobs.vue we want to show all jobs in reverse mode and the first thing that comes to mind is to use, again, reverse(), but this is not the right way to do it. If we take a look in our console we will see the next warning:

[Vue warn]: Maximum recursive updates exceeded in component . This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.

<div v-for="job in jobs.reverse()" :key="job.id">
    <JobComponent />
</div>
Enter fullscreen mode Exit fullscreen mode

Image description


Here is the catch, the right way to do this is to use both slice() & reverse() methods, because:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

<div v-for="job in jobs.slice().reverse()" :key="job.id">
    <JobComponent />
</div>
Enter fullscreen mode Exit fullscreen mode

slice() without any parameters because this time we don't want to shorten the array, we want to show the full array.

Top comments (0)