0

I have an array of object containing colors. I need to sort the array by the color in a specific order.

I used the answer from stackoverflow to sort the array in a specific order and it has mostly worked. The issue that I face right now is that when I visualise it using D3Js, instead of clubbing all the objects with matching colors together there is repetition of the colors in specified order. Why is this happening and how can I get the correct sorting.

    var sortOrder = {"#F39849": 0, "#E94927": 1, "#538296": 2, "#CCCCCC": 3};

    var sortedData = data.sort(function (p1, p2) {
      return sortOrder[p1.colors] - sortOrder[p2.colors];
    });

full code is here

enter image description here

1 Answer 1

0

I'm guessing that this has to do with the values in your data that are don't have colors attributes. There are at least a few of them I see.

If you had some handling for unknown values, say

    var sortOrder = {"#F39849": 0, "#E94927": 1, "#538296": 2, "#CCCCCC": 3, "unknown" : 100};

and

    return sortOrder[p1.colors || 'unknown'] - sortOrder[p2.colors || 'unknown'];

It will likely work.

You might also want to handle the case where colors is found, but is not in your list, which probably can be handled with

return ((sortOrder[p1.colors || 'unknown'] + 1) || Infinity) - 
       ((sortOrder[p2.colors || 'unknown'] + 1) || Infinity);

The Infinitys are to move any not found to the end of the list, and we need to +1s to avoid doing 0 || Infinity.

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

Comments

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.