Arranging the index of an array according to a separate array of objects in JavaScript using Vue

I have two arrays of objects that need to be sorted based on the value of a key in the other array.

        array1: [
            {
                group: 'GROUP1',
                sort_order: 1,
            },
            {
                group: 'GROUP2',
                sort_order: 2,
            },
            {
                group: 'GROUP3',
                sort_order: 3,
            }
        ],
        array2: {
            'GROUP3' : [
                {
                    "price": 10,
                    "amount": 2,
                },
                {
                    "price": 45,
                    "amount": 7,
                },
            ],
            'GROUP2' : [
                {
                    "price": 10,
                    "amount": 2,
                },
                {
                    "price": 45,
                    "amount": 7,
                },
            ],
            'GROUP1' : [
                {
                    "price": 10,
                    "amount": 2,
                },
                {
                    "price": 45,
                    "amount": 7,
                },
            ]
        }

Now, I need to rearrange the indexes of array2 based on the "sort_order" in array1.

I'm anticipating the order of array2 to be something like GROUP1, GROUP2, GROUP3.

Thank you in advance!

Answer №1

const ordered = Object.entries(list2).sort(([groupA], [groupB]) => 
    list1.find(item => item.group === groupA).order - 
    list1.find(item => item.group === groupB).order)

will provide you with

[
    [
        "CATEGORY1",
        [
            {
                "price": 10,
                "quantity": 2
            },
            {
                "price": 45,
                "quantity": 7
            }
        ]
    ],
    [
        "CATEGORY2",
        [
            {
                "price": 10,
                "quantity": 2
            },
            {
                "price": 45,
                "quantity": 7
            }
        ]
    ],
    ...

Answer №2

It seems like you are looking to sort the second array based on the information from the first array. I suggest keeping the original array as it is and performing the sorting operation within a computed property. Here is an example:

const app = new Vue({
  el:'#app',
  data: () => ({
    array1: [
      {
        group: 'GROUP1',
        sort_order: 1,
      },
      {
        group: 'GROUP2',
        sort_order: 2,
      },
      {
        group: 'GROUP3',
        sort_order: 3,
      },
    ],
    array2: {
      'GROUP3' : [
        {
          "price": 10,
          "amount": 2,
        },
        {
          "price": 45,
          "amount": 7,
        },
      ],
      'GROUP2' : [
        {
          "price": 10,
          "amount": 2,
        },
        {
          "price": 45,
          "amount": 7,
        },
      ],
      'GROUP1' : [
        {
          "price": 10,
          "amount": 2,
        },
        {
          "price": 45,
          "amount": 7,
        },
      ],
    },
  }),
  mounted() {
    setTimeout(() => {
      console.log(this.sortedArray2);
    }, 1000);
  },
  computed: {
    sortedArray2() {
      const arr2 = { ...this.array2 };
 
      this.array1.map(item1 => {
        arr2[item1.group] = arr2[item1.group].sort((a, b) => {
          switch(item1.sort_order) {
            case 1: {
              return a.price > b.price ? 1 : -1;
            }
            case 2: {
              return a.price < b.price ? 1 : -1;
            }
            default: {
              return a.amount < b.amount ? 1 : -1;
            }
          }
        });
      });
      
      return arr2;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</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

The animation for the CSS gradient background is failing to animate

After finding a similar code snippet used for backgrounds, I made some modifications to suit my needs. However, when attempting to implement it or any animation, nothing seems to be working. Even simple animations are not functioning as expected. While I a ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

Update the input type on the fly

Hey there, I've got a bit of an unusual question. I'm looking to create a form with fields that vary for each user, like a text input or a checkbox. I attempted using Angular to achieve this: <div ng-controller="myCtrl" ng-repeat="x in prova" ...

What steps should be taken to effectively integrate Amplify Authenticator, Vue2, and Vite?

Embarked on a fresh Vue2 project with Vite as the build tool. My aim is to enforce user login through Cognito using Amplify. However, when I execute npm run dev, I encounter the following issue: VITE v3.1.3 ready in 405 ms ➜ Local: http://127.0.0 ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

How to use JQuery to parse an external JSON file with array elements in Javascript

My goal is to extract information from an external JSON file using JavaScript, specifically an array and other elements. The JSON file I am working with is called 'TotalUsers.json' {"@version":"1.0", "@generatedDate":"12/20/10 5:24 PM", "day":[{ ...

Implement the use of HTML buttons to dynamically change the source attribute of an image using

I am in the process of creating a webpage with 25 different images that will be displayed one at a time. Each image represents unique combinations from two sets of items: (ant, blueberry, ladybug, marshmallow, mushroom) and (blimp, truck, moon, ocean, redw ...

Analyzing Array Elements in a Lottery Simulation using C++

I am currently working on a lottery program and I am facing a challenge in creating a function to compare the user's numbers with the winning numbers. The ultimate goal is to determine the prizes won based on the matching numbers. Although the code co ...

Is it possible to utilize the `useLoaderData` function in ReactRouter v6.9.0 within sibling components of the component where `loader()` is employed? If so, what is the method

In my MoviePage component, I have successfully fetched data using a loader and am utilizing this data with the help of useLoaderData. However, I am facing an issue when trying to access this data in sibling components such as MoviePage/Genre1, MoviePage/Ge ...

Trigger a keypress event following the activation of a button

I've been trying to simulate the press of the backspace key on the keyboard after clicking a button, but all my attempts have been unsuccessful. Here is the code I'm using: function rtf(){ document.getElementById("u0u").focus(); $('#u0u ...

Adjust form elements dynamically depending on the selected option in a dropdown menu using Ruby on Rails

I currently have the following database tables set up: Departments ID| Department_name | Manager_ID Employees ID| Name | Department_ID Salaries ID| Employee_ID | Salary_Amount The departments table holds information about different departments within t ...

Displaying <p> content upon selection of a radio button

As a beginner in JS + HTML, I am looking to create 4 radio buttons with different names like this: o PS4 o Xbox o Nintendo DS When one of these is clicked/checked, I want to display the price which will be located in a "p" tag next to them, like so: o P ...

Displaying dynamic data with Vue.js and Chart.js

I am currently working on a VueJS code to display a bar-chart: Vue.component('bar-chart', { extends: VueChartJs.Bar, data: function () { return { datacollection: { labels: ['MICROFINANZAS -SECTOR C ...

The issue arose with using Numpy hstack where the error message "ValueError: all the input arrays must have the same number of dimensions" was encountered. However,

I am attempting to combine two numpy arrays. One array includes a series of columns/features after applying TF-IDF on a single text column, while the other array contains a single integer column/feature. My approach involves reading in data for training an ...

Leveraging the html-webpack-plugin for creating an index.html file within Webpack (specifically in a project based on the vue-simple boiler

For every build in Webpack, I am attempting to create a customized index.html file. In order to achieve this, I have incorporated html-webpack-plugin. I comprehend that to generate an index.html file within my dist directory, the following configurations ...

Retrieve a specific div element from the response data in AngularJS

Struggling to extract a specific div element from an AJAX response in Angular? Don't want the entire page content to be displayed? Tried various methods but nothing seems to work. Here's what I have attempted: $http({ method: 'GET&a ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Encountering a Project Oxford error - HTTP 404 while trying to access Computer Vision API with Javascript

I am attempting to retrieve JSON data from Microsoft Project Oxford via an API call. Despite following the API reference, I encounter a 404 error when making the call. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">< ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

Determine whether a component is linked to an event listener

If a <Form> component is called with a @cancel event listener attached to it, the cancel button that triggers this event should be visible. If no @cancel event is present, the cancel button should not be displayed. Is there a method to verify if a c ...