ModestMonk ModestMonk - 3 months ago 9
Javascript Question

How do you orderBy using an array as a dictionary

I've been searching for this and can't quite figure out how to word (or just can't find) what I am looking for.

I have two javascript arrays of objects. One has a collection of requests full of IDs, the other contains an array that is basically a dictionary of what those IDs represent. I want to orderBy the requests array by a description_text that lives inside the dictionary array. I am trying to only house the IDs inside the request array as opposed to repeating them 1000 times in each array and am looking for the fastest way to do this.

Example:

$scope.requests = [
{ request_id 1, request_division_id: 1, morefeilds...},
{ request_id 2, request_division_id: 3, morefeilds...},
{ request_id 3, request_division_id: 1, morefeilds...},
{ request_id 4, request_division_id: 2, morefeilds...},
{ request_id 5, request_division_id: 4, morefeilds...}];
$scope.divDict = [
{request_division_id: 1, desc_text: 'Sahara Square'},
{request_division_id: 2, desc_text: 'Little Rodentia'},
{request_division_id: 3, desc_text: 'Rainforest District'},
{request_division_id: 4, desc_text: 'Tundratown'},]


So in this case I would need the orderby to return sorted in this order:

$scope.requests = [
{ request_id 4, request_division_id: 2, morefeilds...},
{ request_id 2, request_division_id: 3, morefeilds...},
{ request_id 1, request_division_id: 1, morefeilds...},
{ request_id 3, request_division_id: 1, morefeilds...},
{ request_id 5, request_division_id: 4, morefeilds...}];


As that is the alphabetical order according to each id's desc_text.

Answer

This is not very different from sorting as if the request housed the desc_text property: rather than resolving the description from the object in the array you will resolve it from the divDict object map.

$scope.requests = $scope.requests.sort(function (req1, req2) {
    let desc1 = $scope.divDict[req1.request_id].desc_text,
        desc2 = $scope.divDict[req2.request_id].desc_text;

    return desc1 < desc2? -1 : +(desc1 > desc2);
});

EDIT:

I had not carefully read the code and expected the divDict to be an object map where the keys would be the request IDs, but I think you will still get the idea.