Ad

You are given an array of Gem objects. Each Gem has a name attribute, and a colors attribute containing either a string, or an array of strings describing its color.

gems = [
  { name: 'Amethyst', colors: 'purple' },
  { name: 'Garnet', colors: ['orange', 'red']},
  { name: 'Aquamarine', colors: ['blue', 'green']}
];

Your task is to create a function getGemsOfColor which takes a color string and a gems array as its argument, and returns the names of the gems of that color as an array, sorted alphabetically. If no gems of the given color are found, return an empty array.

Assumptions

  • The colors property of each gem is never undefined.
  • The gems input array is never empty.

Examples:

Given input array: gems = [
  { name: 'Amethyst', colors: 'purple' },
  { name: 'Garnet', colors: ['orange', 'red']},
  { name: 'Aquamarine', colors: ['blue', 'green']},
  { name: 'Emerald', colors: 'green' },
];

getGemsOfColor('blue', gems) // ['Aquamarine']
getGemsOfColor('green', gems) // ['Aquamarine', 'Emerald']
getGemsOfColor('white', gems) // []
function getGemsOfColor(color, gems) {

}

I suggest first converting the string to lower case so you don't need to add the conditional for checking for the uppercase 'A'.

Code
Diff
  • count=str=>str.toLowerCase().split("").filter(x=>x=="a").length;
    • count=str=>str.split("").filter(x=>x=="a"||x=="A").length;
    • count=str=>str.toLowerCase().split("").filter(x=>x=="a").length;