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.