Order a nested array according to the inner value, using a different array as a reference

Having two arrays at hand, array1 requires sorting based on its inner key, role, as per array2. Despite attempting various solutions, I have hit a roadblock due to my lack of understanding on the necessary steps to proceed.

The current output for Array1 is as follows:

{
      "id":12,
      "roles":[
         {
            "id":12,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"LWB"
               }
            }
         }
      ],
      "user_email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681f281f461f">[email protected]</a>"
   },
   {
      "id":1575,
      "roles":[
         {
            "id":1672,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"LB"
               }
            }
         }
      ],
      "user_email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026842682c71">[email protected]</a>"
   },
   {
      "id":1576,
      "roles":[
         {
            "id":1673,
            "role":"team_player",
            "sub_role":null,
            "team_meta":{
               "default_player_role":{
                  "pos":null,
                  "role":"CAM"
               }
            }
         }
      ],
      "user_email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="084d484d264d">[email protected]</a>",
   },

My objective is to reorder the array above based on the sequence provided in:

const array2 = ["LWB", "LB", "CAM"]

The challenge I am facing is that the sorting key in array1 is too nested, and I am struggling to map the "role" from the first array with array2.

Answer №1

To determine the order, you must retrieve the role and use its value to find the index.

const
    getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role,
    data = [{ id: 1576, roles: [{ id: 1673, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "CAM" } }], user_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f4a4f4a214a">[email protected]</a>" }, { id: 12, roles: [{ id: 12, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LWB" } }], user_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047344732a73">[email protected]</a>" }, { id: 1575, roles: [{ id: 1672, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LB" } }], user_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="224862480c51">[email protected]</a>" }],
    order = ["LWB", "LB", "CAM"];

data.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b)));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Through multiple iterations, a less than elegant sorting solution can be achieved:

const randomizedNestedArray = [...]; // Update Array 
const sortByArray = ["LWB", "LB", "CAM"];
const organizedArray = [];

sortByArray.forEach((sortByItem) => {
    randomizedNestedArray.forEach((nestedItem) => {
        nestedItem.roles.forEach((role) => {
            if (role.team_meta.default_player_role.role === sortByItem) {
                organizedArray.push(nestedItem);
            }
        });
    });
});

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

Adjust the viewing area dimensions on a web browser

Recently, while testing a web application page I developed with Selenium, I came across an interesting issue. After using the JavaScriptExecutor in Selenium to get the viewport size, I found that it was different for Chrome, IE, and Firefox. The sizes wer ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

Issue with Observable binding, not receiving all child property values in View

When viewing my knockout bound view, I noticed that not all values are being displayed. Here is the script file I am using: var ViewModel = function () { var self = this; self.games = ko.observableArray(); self.error = ko.observable(); se ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

The attempt to compress the code in the file from './node_modules/num2persian' using num2persian was unsuccessful

I have been using the num2persian library to convert numbers into Persian characters. However, whenever I run the command npm run build, I encounter the following error: An error occurred while trying to minimize the code in this file: ./node_modules/num ...

JavaScript Transcriber

Hey there! I'm currently attempting to compile some JavaScript code that I have written in a textarea and get the output of this code. I've tried using the eval() method, but unfortunately, I haven't been able to get the complete response. C ...

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...

Successful execution of asynchronous method in Node.js without any errors

When encountering duplicates in the config, I use the code snippet below: require('./ut/valid').validateFile() }); If a duplicate is found during validation, an error is sent like so: module.exports = { validateFile: function (req) { ... ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Using TypeScript, the fetch function cannot be assigned

Why am I encountering this TS warning? Type 'unknown' is not assignable to type 'PokemonList'.ts(2322) This issue is on line: "return e" Here is the code snippet: export interface PokemonList { count: number; next: stri ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

Graph only displays data after button is clicked

I have been working on customizing this jsfiddle to display database data. Check it out here: http://jsfiddle.net/jlbriggs/7ntyzo6u/ Using JSON, I am fetching data from my database and editing chart1 to display the database data: var chart, chartOption ...

What is the best way to update data by making API calls within store.js using Vuex?

I am in the process of integrating vuex into my project. I have familiarized myself with mutations and actions for updating state properties. My main inquiry is regarding the most secure and effective method to update state components by retrieving data fr ...

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

execute javascript code after loading ajax content

Although this question may have been asked before, I am completely unfamiliar with the subject and unable to apply the existing answers. Despite following tutorials for every script on my page, I have encountered a problem. Specifically, I have a section w ...

Android Webview onLoad function provides incorrect height information

When I load a file:// URL into the webview, issues with height calculation arise. Instead of using WRAP_CONTENT, I calculate the height in javascript during the onPageFinished event in Android. However, about 2 out of 5 times, the javascript reports an inc ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Saving Arrays through an Input Form in JavaScript

I am working with an HTML form that looks like the following: <div class="form-group"> <label for="first_name">1st Name</label> <input type="text" id="first_name" placeholder="First Name" class="form-control"/> </div> ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...