Issue at hand: I am faced with a situation where I have an array of objects that need to be sorted in ASC DESC order based on one of the object keys. Following this, I also need to sort an array of strings in the same manner as the array of objects. For example:
arrayOfObjects = [{name:"john",number:6,food:"pizza"},
{name:"david",number:2,food:"gulash"},
{name:"margaret",number:7,food:"gugi berries"}]
arrayOfStrings = ['r1','r2','r3']
Each object in arrayOfObjects corresponds to a string in arrayOfStrings. For instance, John is associated with r1 and they are first in their respective arrays. However, when I sort by number, John gets moved to the second position. In this case, I want his corresponding string 'r1' to also move to the second position, along with David and Margaret's numbers.
The goal is to rearrange the arrayOfStrings in the exact order that the arrayOfObjects was sorted, regardless of the sorting criteria used for the objects.
Here is my sorting function :
dataArray.sort(dynamicSort(sortBy));
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
if(direction=='asc'){
var c = b;
b=a;
a=c;
}
var result = ( b[property] < a[property]) ? -1 : ( b[property]> a[property]) ? 1 : 0;
return result * sortOrder;
}
}