The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios.

 bannerData= [
        {
          "id": 118,
          "title": "Geruchsbel\u00e4stigung",
          "location": "DOR",
          "pressInformation": [
            {
                "id": 257,
                "title": "Chemi257"
              },
              {
               "id": 256,
               "title": "Chemi256",
              }
          ]
        },
        {
          "id": 144,
          "title": "Testing Stage",
          "location": "LEV",
          "pressInformation": [
            {
              "id": 254,
               "title": "Chemi254",
            },
            {
              "id": 261,
               "title": "Chemi261",
            }
          ]
        }
      ]
computed: {
    orderedUsers: function() {
      this.secondSubBanner = [];
      for (let i = 0; i < this.bannerData.length; i++) {
        this.subBanner = this.bannerData[i].pressInformation;
        for (let j = 0; j < this.subBanner.length; j++) {
          this.secondSubBanner.push(this.subBanner[j].id);
          console.log(this.secondSubBanner); // output: 257, 256, 254,261
        }
      }
      return this.secondSubBanner;
    },
sortedArray() {
      let v = this.orderedUsers.sort();
      console.log(v); // output: 254, 256, 257, 261
      return _.orderBy(this.bannerData, v)
    }

sortedArray prints the id's in order using sort(), but it doesn't properly order the Json properties depending on _.orderBy(). Can someone point out my mistake?

Answer â„–1

Check out this algorithm that could suit your needs without the need for lodash. By simply using the flatMap() and sort() functions available, you can achieve the desired outcome:

function sortedArray(bannerData) {
  const array = bannerData.flatMap(x => x.pressInformation)
  return array.sort( (a,b) => a.id - b.id )
}

bannerData = [
  {
    "id": 118,
    "title": "Geruchsbelästigung",
    "location": "DOR",
    "pressInformation": [
      {
        "id": 257,
        "title": "Chemi257"
      },
      {
        "id": 256,
        "title": "Chemi256",
      }
    ]
  },
  {
    "id": 144,
    "title": "Testing Stage",
    "location": "LEV",
    "pressInformation": [
      {
        "id": 254,
        "title": "Chemi254",
      },
      {
        "id": 261,
        "title": "Chemi261",
      }
    ]
  }
]

console.log(sortedArray(bannerData))

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

Encountering a snag when trying to load JavaScript within an HTML document

I encountered an error while trying to load an HTML file in the JavaScript console of the Brave browser. The error message reads: require.js:5 Uncaught Error: Module name "constants.js" has not been loaded yet for context: _. Use require([]) https://requir ...

Facebook pages and tabs utilize the [fbjs] JavaScript library

I am struggling to implement tabbing functionality on a Facebook application (business) tabs. Despite having some basic HTML and JS [fbjs], the code I have doesn't seem to be working. I can't figure out what is wrong. <div id="foo">foo di ...

Show a Kendo Pie Chart that reflects information from the grid dataset

I am using KendoUI - Grid component Is there a way to transform this into a Kendo Grid? For example: I have set up a Kendo grid (table) with local data. When I click on the "Generate chart" button, I want the filtered data from the table to be used to cr ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

Unable to upload file on ReactJS platform

I'm facing an issue while trying to upload a file and text using a form. The file doesn't get uploaded, although it works fine with Postman. Can anyone identify the problem? Thank you Axios function : postArticles : (content, attachment, header ...

If the browser is Internet Explorer, then load file [A]; otherwise, load file [B]

One of my webpages requires unique content to be loaded for different web browsers. For example: If the browser is Internet Explorer {include file="/content1.tpl"} Else if it's any other browser {include file="/content2.tpl"} {/if} Content1. ...

Attempting to retrieve an element by its ID from a div that was dynamically loaded using AJAX

I am having trouble retrieving the value of an element with getElementById from a div that is loaded via ajax. Let me explain: In 'example.php' I have the following JavaScript code: <script type= "text/javascript"> var page=document.getE ...

Unable to fetch valid JSON from a different domain using JQuery and AJAX

I'm having trouble accessing a JSON api from a specific adult-themed website. I've been trying to make it work but so far no luck. You can find my code snippet in this jsfiddle: http://jsfiddle.net/SSqwd/ and here is the script: $.ajax({url: &ap ...

Triggering transitionend event once with an added if condition

Currently, I have an application of an if statement that examines whether an element contains a style attribute. In the event that the style attribute is absent, it appends inline styling. Conversely, if the style attribute exists, it is removed. Furthermo ...

A guide to monitoring and managing errors in the react-admin dataProvider

Rollbar has been successfully integrated into my react-admin app to track uncaught errors. However, I've noticed that errors thrown by the dataProvider are not being sent to Rollbar. It seems like errors from the dataProvider are internally handled w ...

AngularJS Update Parent-Child Relationship: Enhancing the Details

When Panel header is clicked, I want to update the respective Panel body with the corresponding data. In my Angular code on Plunker, clicking "Test1" should only update "Test1detail" in the body. Click here for the Plunker Here's the code snippet fr ...

Assign a class to the initial element of the Vuetify v-select module

Hey there! Currently, I'm utilizing the v-select component from Vuetify. I'm looking to customize the appearance of the first item in the v-select component by adding a specific class. For example, I want the text of the first entry "Item A" to b ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...

Why is the output showing as abnormal?

There are occasions when I am unable to successfully execute this script! var b = [9,8,7,6,5,4,3,2,1]; var a = (function(){ var W = []; for(var k in b){ W[W.length] = { index : k, fx : function(){ console.log(k); ...

Obtain the present location of the cursor within the TinyMCE editor

Despite various attempts, I have struggled to determine the current cursor position inside TinyMCE. My goal is to implement a change control feature that captures the starting point of text entry within the TinyMCE "textarea," allowing me to save the ente ...

Extracting information from the callback function

As I utilize AngularJS, I find myself constantly facing the challenge of managing asynchronous behavior and callback functions. How can I adjust PostsService.getPostBySlug to retrieve the desired post below? Custom Posts service Website.factory( 'Po ...

experiencing difficulties in retrieving the outcome from a sweetalert2 popup

function confirmation() { swal.fire({ title: "Are you absolutely certain?", text: "You are about to permanently delete important files", type: "warning", showCancelButton: true, show ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Error message encountered on localhost: preflight response contains Access-Control-Allow-Headers issue

I'm currently working on my React app locally at localhost:3000 and utilizing this code snippet: try { const response = await fetch('https://myendpoint.com/abcd/search?c=abc123', { headers: { 'Content-Type': 'application ...

Ensuring secure authentication in your Vue.js application using Vue router and Django

When it comes to checking if a user is authenticated on protected routes in vue-router, I have a setup using Django rest framework that sets sessionid upon login. While some users opt to use vuex or local storage to store session information, there's ...