Determine in VueJS v-for loop if the previous element in the object has changed, such as switching cities

I'm facing a dilemma here... I have an array structured like this:


[{'city':'LA','store':'Bobs Burgers'},{'city':'LA','store':'Burger King'},{'city':'Sacramento','store':'Jimmy Burger'}]

While iterating through these burger joints in a table, I need to insert a row whenever the city changes. How can I achieve this?

In PHP, the solution would look something like this:


<?php
foreach ($store in $burgerplaces){

if ($store['city']!=$prev_city){
   # display header for the city 
}

#print store info

$prev_city=$store['city'];

}
?>

Answer №1

If I have correctly understood your instructions, you can achieve the desired outcome by using the code snippet below (in the computed property, sort your array first and then loop to compare cities and add an empty object before moving on to the next city):

new Vue({
  el: "#demo",
  data() {
    return {
      burgers: [{'city':'LA','store':'Bobs Burgers'},{'city':'Sacramento','store':'Jimmy Burger'},{'city':'LA','store':'Burger King'}, {'city':'NY','store':'Burgers'}]
    }
  },
  computed: {
    byCities() {
      const arr = this.burgers.sort((a,b) => {
        const nameA = a.city.toUpperCase();
        const nameB = b.city.toUpperCase(); 
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }
        return 0;
      })
      const res = []
      for(let i = 0; i < arr.length; i++){
        if (i ===0 || arr[i].city !== arr[i-1].city) {
          res.push({city: arr[i].city.toUpperCase()})
        }
        res.push(arr[i])
      }
      return res
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <li v-for="(burger, i) in byCities" :key="i">
    {{ burger.city }}  {{ burger.store }}
  </li>
</div>

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

Dynamically changing click events in VueJS can be achieved using a combination of

Once component B has finished loading, I trigger an "emit" event to notify component A using EventBus. When A receives the event with a value of "on", it updates a specific data value to true. This value is stored in a computed property and can only be a ...

In Snowflake, SQL error handling block fails to execute

Implementing error handling in Snowflake using a Try Catch block has been my focus. I've enclosed SQL queries within JavaScript for this purpose. However, upon executing the query, I noticed that it skips the Try Catch block and directly executes the ...

Retrieve a collection of items based on their data-id attribute

I need to create a list of label elements with data-id attributes. I will use the values from these labels to set images on the main container. The function changeimage is returning a nodelist with null elements, but I am not sure why this is happening. ...

Execute two different functions in AngularJS using ng-click in any order

There is a button labeled Modify. When clicked, the modify() function is triggered and the text on the button changes to Save. Clicking on it again will execute the save() function. Below are the codes: <button class="btn btn-primary" ng-click="modify ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

Stop Jade from collapsing the directory hierarchy

When it comes to implementing a build solution using NPM scripts instead of Gulp or Grunt, I have been facing some challenges in managing multiple Jade files efficiently. I've referred to resources like and for guidance. The Jade CLI allows for com ...

Encountering CORS issues, but rest assured I have it enabled

I recently encountered a CORS error when trying to make a request from a v-autocomplete component during a keydown event. Strangely, this issue only occurs in that specific scenario and I'm not sure what the reason could be. Interestingly, if I try to ...

Transforming an array of flat data into a hierarchical tree structure

I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj. The Rules are: If an object has a higher depth, it should be a child of an object with a l ...

A guide on utilizing a looped event listener with a function to switch object textures in THREE.JS

Currently working on a Webgl 3D project, the task at hand is to dynamically change the textures of a loaded COLLADA object by clicking on buttons associated with each texture. Up until now, I've successfully achieved this with three textures by dupli ...

Eliminate item from array based on certain criteria

In certain scenarios, I must update the filters. Under specific data conditions, I am required to eliminate 1 item from an array. Here is the code snippet: useEffect(() => { let canceled = false; const filters = [ new C ...

Safari's anchor links tend to leap higher than necessary

One of the anchor links on my website is behaving strangely in Safari, both on iPhone and MacOS. Instead of scrolling to the correct position of the anchored div, it scrolls to a random location around 400-500px higher than it should be. All other anchor l ...

Send pages to the holding page first before redirecting them to the appropriate page on the new website

I am in the process of updating my old website (www.old.com) with a new one that has similar pages (www.new.com). I want all the pages from www.old.com to automatically redirect to a temporary holding page (a basic html page with a countdown script and red ...

Encountering a "Cannot read property 'addEventListener' of null" error while working on a dynamic table using JavaScript

I am trying to dynamically create a table on a webpage using JavaScript, but I'm running into some issues. Specifically, I can't use .appendChild and when I ran my script through JSLint, it gave me an error about the 'createTable' funct ...

Embed a Vaadin component within an element dynamically generated by a Javascript component

I am currently designing a Vaadin application and working on a custom Javascript component, which is a subclass of AbstractJavascriptComponent. This component uses jQuery to generate a table-like structure. In certain scenarios, users should be able to in ...

Seeking a way to access Json parse with special characters?

I'm facing a challenge with the JSON output below, specifically when dealing with certain characters. JSON String { "results": { "RESULT1-Node1": { "Network.MS": "405", "Down_time": "131" }, "RESU ...

When attempting to access an API hosted on Cloudflare from Heroku, a 403 error is returned

I am currently utilizing the Cowin API () to access available slots. My implementation is based on Node.js. Interestingly, it functions well on my local machine but encounters an error after deployment on Heroku. 2021-05-09T11:07:00.862504+00:00 app[web.1] ...

Refresh a gif animation when the page is reloaded

I have a website that features a div with a dynamic gif image as the background. The gif animation is set to play only on the initial page load. However, if the page is refreshed or navigated back to the homepage from another page, the animation does not ...

Encountering a PDF loading error when integrating ReactPDF in a React project

Having trouble trying to display a PDF file using the PdfReact component. Every time I attempt to load the PDF, I encounter the following error: Warning: Ignoring invalid character "114" in hex strinpdf.worker.js:342 Warning: Ignoring invalid character " ...

At which location within the script should I insert the document.title in order to update the title every xx milliseconds?

I have been working on a script that refreshes certain #id's. Additionally, I would like to update the page title, which involves some flask/jinja2. I've attempted placing document.title = {% block title %} ({{online_num}}) Online Players {% en ...

Solution for problem with IE scrollWidth

Encountered a peculiar bug in IE where the scrollWidth is consistently off by 1px compared to the offsetWidth. This anomaly appears to be triggered by the length of text/characters within the element, specifically when overflow is set to something other th ...