Guide on organizing a multi-dimensional array of objects based on property value using javascript?

I am faced with the challenge of sorting a multidimensional array based on values, but the selection is dependent on the parentID.

This is my current array:

const result = [
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
]

Here's what I have attempted:

const parentID = 1;
const sortedResult = result.filter((row) => {
  const selectedColumn = row.find((column) => column.parentID === parentID));
  return _.orderBy(selectedColumn, ['value'], ['asc']);
});

Unfortunately, this approach does not yield the desired outcome. Any suggestions on how to correct it?

The expected result should be:

[
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
]

Answer №1

One way to effectively sort an array is by using the Array.prototype.sort method.

To achieve this, it's recommended to create a helper function that takes in an array item (which is itself an array) and locates the object with the specific parentID, extracting its corresponding value. Within the callback function of the .sort method, invoke this helper function on both items being compared and return the resulting difference:

const parentID = 1;
const getValue = arr => arr.find(item => item.parentID === parentID).value;
const result = [
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
];
result.sort((a, b) => getValue(a) - getValue(b));
console.log(result);

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 hot loader is replicating code multiple times instead of conducting hot swapping

Every time I make a change in a component, webpack recompiles and React hot swaps the module over. However, I've noticed that my code runs multiple times after each hot module swapping occurrence. For example, if I make a change once, the functions ru ...

php executing javascript - error

I have a question regarding my PHP file code: echo '<script type="text/javascript">'; echo '<audio id="player" src="../cdh/ba1.mp3"></audio>'; echo '<a onclick="document.getElementById( ...

Find the total number of elements in the given ArrayList

I am working with an ArrayList that contains a collection of cars in inventory. The goal is to have the user input a start year and end year, and then determine the number of cars within that specified year range. Using a foreach loop, I need to display ...

Is your Firebase Google sign-in popup window flashing and not successfully signing in while using Vue.js?

After implementing the Google sign-in pop-up method in Vue.js, I encountered an issue where the live Google sign-in popup window kept flashing and never successfully signed in. However, this problem did not occur when testing locally. Below is the code fo ...

There is a complete absence of text appearing on the html page when Angular is

Currently, I am in the process of learning Angular during my internship. As part of the requirements, I have been tasked with developing a client-server application using Angular as the frontend framework and Spring as the backend solution. Within the proj ...

Tips on transferring information to the graphical user interface

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...

Removing items in vue.js

I'm currently in the process of learning Vue.js. This is my first attempt at creating a small to-do application, and I am encountering issues with deleting each individual task upon clicking. Despite watching multiple YouTube tutorials, I have not bee ...

What is the best way to transform an array of arrays into an array of objects using AngularJS?

Here is some code I am working on: $scope.students=[]; $scope.students[[object Object][object Object]] [0]{"id":"101","name":"one","marks":"67"} [1]{"id":"102","name":"two","marks":"89"} I would like to reformat it into the ...

Using CSS, center a div element both vertically and horizontally, and position the footer at the bottom of the page

I am encountering some unexpected behavior for a task that I thought would be simple. I have two main objectives in mind. Firstly, I want the footer to be displayed at the bottom of the page as an actual footer. Secondly, I need the div with the ".center-d ...

What is the significance of incorporating react context, createContext, useContext, and useStore in Mobx?

In my Typescript application, I rely on Mobx for persistence and have created a singleton class called MyStore to manage the store: export class MyStore { @observable something; @observable somethingElse; } export myStore:MyStore = new MyStore(); ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

Adjusting the timeout value for axios does not produce any impact

In our code, the timeout is configured as follows: axios.defaults.timeout === 3000; ...... try { const response = await axios.get(Url, { headers: { 'Authorization': authToken.authHeaderValue, } ...

NextJS API Generator for OpenAPI specifications

In my NextJS project, we utilize the /api path to implement our API, with an openapi.yaml file defining the interface. To generate the API client successfully, we run the following command: openapi-generator-cli generate -i data/api/openapi.yaml -o src/api ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

Puppeteer cluster crashes unexpectedly upon invoking cluster.close() following cluster.queue() execution

So here's the deal - I developed an app for web scraping that requires the ability to run multiple processes simultaneously (more than one Chromium instance). To achieve this, I implemented puppeteer-cluster. While I successfully managed to initiate s ...

Converting an integer value into an array in C to generate the following 10 octal numbers is not possible

I am trying to develop a program that takes a 4-digit octal number as input and then outputs the next 10 octal numbers. Despite not encountering any errors, my code fails to convert the entered number into an array, preventing it from displaying the subs ...