Tips for organizing an array with mixed data types using JavaScript

I'm still learning JavaScript, and I'm struggling with sorting an array. Let's say I have two arrays like this:

var mergedArray = result.Entities.concat(result.NonClickablePaths);
var allPaths = result.AllPaths;

The data in both arrays looks like this:


mergedArray  = [{obj1}, {obj2}, 'xyz'];
AllPaths =  [ 'abc', 'xyz', 'wxy'];

In this scenario, the values in AllPaths exist within the objects in mergedArray like so: obj1.coords = 'abc' and obj2.coords = 'wxy'.
The current order of mergedArray is obj1 at index 0, obj2 at index 1, and the string 'xyz' at the final index. Now, I want to sort mergedArray based on the values' order in AllPaths.

Is it possible to achieve this sorting functionality?

The expected outcome of this sorting operation is to arrange mergedArray according to the order of values in AllPaths:
Output:

mergedArray = [{obj1}, 'xyz', {obj2}];

I've tried sorting it in the following way, but it didn't produce the desired result:
Here is what I attempted:

mergedArray.sort(function(a, b) {
  var aCoord = (typeof a === 'object') ? a.coords : a;
  var bCoord = (typeof b === 'object') ? b.coords : b;
  return allPaths.indexOf(aCoord) - allPaths.indexOf(bCoord);
});

After using this built-in sort function in JavaScript to compare the coordinates, the structure of the data remained unchanged after sorting, with no noticeable differences.

Note: I'm currently stuck on how to properly sort this array in the desired manner. Any advice or guidance would be greatly appreciated. Thank you all.

Answer №1

I reviewed your code and found that the sorting functionality is working correctly based on the provided data. You can view the cleaned up code on this jsfiddle link, where I made some optimizations like using const and || to simplify the ternary operator. It seems that the discrepancy may lie in the structure of obj1 and obj2 compared to your expectations, as shown in the following:

mergedArray = [{obj1}, {obj2}, 'xyz'];

This shorthand is equivalent to:

mergedArray = [{
  obj1: {
    coords: 'abc'
  },
  obj2: {
    coords: 'wxy'
  },
  'xyz'
]

If this is indeed the structure of the array, you will need to access the parent object in order to retrieve the coords property. You can achieve this by doing:

const aCoord = typeof a == 'object' ? Object.values(a).find(e => !!e.coords).coords : a;

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 created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

Establishing the root directory for imports in Angular 2

Currently, I am building an Angular2 application using version 2.0.0-beta.7 along with TypeScript. Initially, I had all my .ts files in a single directory for quick functionality access. However, now I am striving to reorganize them logically within a dire ...

What is the best way to convert a string array KEY to numbers based on the length of the array in PHP

In my PHP code, I have an array structured like this: Array ( [Cpu] => Cpu [Memory] => Memory [Ping] => Ping [Interface - Ethernet] => Interface - Ethernet [Disk - C:] => Disk - C: [Disk Reponse - C] => Disk Repons ...

The Journey of React Native Routing

When building my React Native application, I encountered a challenge with creating a Footer and Tab menu that should only be displayed on certain screens. If I define them within the NavigationContainer, they apply to all screens uniformly. How can I sep ...

Do the Push Notification APIs in Chrome and Firefox OS follow the same set of guidelines and standards?

Do Chrome and Firefox OS both use Push Notifications APIs that adhere to the same standard? If not, is either one moving towards standardization? ...

TS2688 Error: Type definition file for 'tooltip.js' not found

Why am I getting an 'undefined' error when trying to import the Tooltip class from the npm tooltip.js package in my TypeScript file? ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

Using jQuery to detect changes in the value of form fields, excluding any changes related to display toggles

Currently, I am in the process of revamping a large form that includes various input fields and dropdown menus. The goal is to submit it via AJAX once a field loses focus but only if the value has been altered. To achieve this, I have set up a jQuery selec ...

Despite receiving the response, the AJAX GET request is still encountering an error

I'm having an issue with a GET request to fetch JSON from an API for my website. Despite displaying the response correctly in the network tab of the Console and showing a 200 status (images attached), it keeps resulting in an error. I've verified ...

Modifying the value upon saving in Adonis JS model

Using Adonis js I am facing an issue when trying to convert an ISO string to Datetime while saving data (the opposite of serializing DateTime fields to ISO string). I cannot find a way to do this in the model, like I would with a mutator in Laravel. Whene ...

Validate form for radio group

Hello Experts, I am currently working on developing a form that includes a JavaScript validation function for a radio group. The main objective is to have a division pop up when either "Monday" or "Tuesday" is checked, and no popup when "None" is selected ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...

What is the best way to maintain the selected row during pagination in Yii?

Currently, I am facing an issue with pagination while viewing table rows. My requirement is to select different rows from various pages and then submit the form. The problem occurs when I select rows from one page, navigate to another page to make more se ...

Sending files via an Ajax request triggers an unexpected page refresh

I have limited experience with ajax, but I am encountering an issue when trying to send form data to an ASP controller. Scenario 1 When I set data in the ajax request to $(this).serialize() All form data is successfully posted to the controller withou ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

What is the best approach for creating a brute-force solution for finding the smallest change algorithm

Looking for a solution to this algorithm challenge: Create a function that can determine the minimum amount of change that cannot be made with the given coins. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: https://i.sstatic.net/iy0ZV.png https://i.sstatic.net/trfrL.png Here is my ...

Running a PHP function within a PHP environment

After the user clicks the submit button and no errors are present, a token value input is generated in the script below. The goal is to post this value inside a php page for use in a query. While the input value is successfully generated, posting it to the ...