4

My problem: I have an array of objects which I sort ASC DESC by one of the objects keys, after that I need to sort an array of string that will be sorted the way the object array has been sort. 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']

so each object in arrayOfObjects has its own string. so say, john has r1, and they are both first indexed, when I sort by number john goes second, and I want hes number to go second as well (as well as david and margaret numbers)

I need to re-arrange the arrayOfStrings the same way (I dont care what it was sorted by) the arrayOfObjects was sorted

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;
    }
}
1
  • 1
    You could add a property to your objects that will be sorted, like {name:"john", r:'r1' ... and then retrieve these values when the array is sorted. Commented Jul 20, 2015 at 9:57

1 Answer 1

2

I suggest you zip the list in the format [[object, string], ...] and then sort according to the first element of the tuple. You can unzip the list afterwards.

Sign up to request clarification or add additional context in comments.

4 Comments

That is a good idea, I had a similar one, just to add each string to its original object, at the key:string and to read it from there. though I wanted to see if there is a way I can 'remember what the the sort changed'
@nadiTime No, I'm pretty sure there isn't, it's not practical at all. I mean at best you'd be doing the sorting work twice which is not something that you want. Just do it all in one go -- either way will do (your or mine), it's just a matter of whether it makes sense for the string to be a part of the object or not.
your absolutely right, I don't want to sort the array again. thanks
@nadiTime If that's it then, you can accept the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.