How to sort one array the same as another?

My problem: I have an array of objects that I sort ASC DESC with one of the keys of the objects, after which I need to sort the array of strings that will be sorted the way the array of objects was sorted. Example:

arrayOfObjects = [{name:"john",nuber:6,food:"pizza"},
               {name:"david",nuber:2,food:"gulash"},
               {name:"margaret",nuber:7,food:"gugi barries"}]

arrayOfStrings = ['r1','r2','r3']

therefore, each object in arrayOfObjects has its own row. so let's say john has r1, and they are both indexed first, when I sort by john number comes second and I want the hes number to also take second place (as well as the numbers of David and Margaret)

I need to rebuild arrayOfStrings in the same way (I don't care what it sorted), sorted arrayOfObjects

My sort 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;
    }
}
+4
source share
1 answer

[[object, string], ...], . .

+2

Source: https://habr.com/ru/post/1598671/


All Articles