Javascript function to return an array that needs to be in a specific order, depending on the order of a different array I have an array of objects, reviews which I get from an API endpoint. This object looks like this:
[
  { name: &quot;Facebook&quot;, count: 50 },
  { name: &quot;Google&quot;, count: 43 },
  { name: &quot;TripAdvisor&quot;, count: 67 },
  { name: &quot;Other&quot;, count: 130 }
]

I have a chart.js Pie chart that I'm feeding this data to. I'm using the name for the labels and the count for the size of each slice of the pie chart. Now, due to how chart.js works, I have to supply some hexadecimal colors to use as background colors, and the order in which the background color is being defined matters if I want the labels to match the colors properly. For example, if the order of the labels is [A, B, C], an array of colors like [red, green, blue] means that A = red, B = green and C = blue. The problem is that the reviews array comes in a random order every single time from the API (I don't have control over the API and the data it gives me), so I can't just have a simple, predetermined array.
As far as I see, I have two options, I either sort the reviews array in some way, or I iterate over the data I get from the API and return an array based on some simple switch statements. I opted for the 2nd option, as it seems simpler for my usecase.
My current solution looks like this
const chartBackgroundColor = collection =&gt; {
  let colorArray = [];
  const itemArray = collection.map(data =&gt; data.name);
  itemArray.forEach(item =&gt; {
      switch (item) {
        case &quot;TripAdvisor&quot;:
          colorArray.push(&quot;#00B98B&quot;);
          break;
        case &quot;Google&quot;:
          colorArray.push(&quot;#FFBD00&quot;);
          break;
        case &quot;Facebook&quot;:
          colorArray.push(&quot;#4B6DAA&quot;);
          break;
        default:
          colorArray.push(&quot;#D9D9D9&quot;);
          break;
      }
    }
  )
  return colorArray;
}

The method works fine, but I was just curious whether there was some more elegant way of handling this issue, and whether a switch case is appropriate in this situation rather than a if/ifel/else tree.
I would

Encapsulate the names and colors in a data structure
Use .map instead of .forEach

So something like this;
function chartBackgroundColor(collection){
  const nameColorMap = {
    &quot;TripAdvisor&quot;: &quot;#00B98B&quot;,
    &quot;Google&quot;: &quot;#FFBD00&quot;,
    &quot;Facebook&quot;: &quot;#4B6DAA&quot;,
  };
  return collection.map(data =&gt; nameColorMap[data.name] || &quot;#D9D9D9&quot;);
}