How to sort the index of objects in array by values in each object sequentially

Solution for How to sort the index of objects in array by values in each object sequentially
is Given Below:

I have this array of objects. Each contain a color and a “weight” value. The weight value for each color will always be dynamic because it depends what image was analysed. I want to sort this array so that the objects with the highest weight value are at the start of the array, and the objects with the lowest weight values are at the end of the array. So that all I have to do to list the top 3 colors is index the first three objects in the array. They need to be objects so I can also log the name of the color with it’s corresponding weight value.

var colors = [
      { name: "Red", weight: red },
      { name: "scarlet", weight: scarletWeight },
      { name: "orangeRed", weight: orangeRedWeight },
      { name: "vermilion", weight: vermilionWeight },
      { name: "internationalOrange", weight: internationalOrangeWeight },
      { name: "safetyOrange", weight: safetyOrangeWeight },
      { name: "darkOrange", weight: darkOrangeWeight },
      { name: "orangePeel", weight: orangePeelWeight },
      { name: "orange", weight: orangeWeight },
      { name: "selectiveYellow", weight: selectiveYellowWeight },
      { name: "goldenPoppy", weight: goldenPoppyWeight },
      { name: "tangerineYellow", weight: tangerineYellowWeight },
      { name: "gold", weight: goldWeight },
      { name: "schoolBusYellow", weight: schoolBusYellowWeight },
      { name: "goldenYellow", weight: goldenYellowWeight },
      { name: "yellow", weight: yellow },
      { name: "chartreuseYellow", weight: chartreuseYellowWeight },
      { name: "electricLime", weight: electricLimeWeight },
      { name: "springBud", weight: springBudWeight },
      { name: "chartreuse", weight: chartreuseWeight },
      { name: "lawnGreen", weight: lawnGreenWeight },
      { name: "brightGreen", weight: brightGreenWeight },
      { name: "harlequin", weight: harlequinWeight },
      { name: "lime", weight: limeWeight },
      { name: "freeSpeechGreen", weight: freeSpeechGreenWeight },
      { name: "malachite", weight: malachiteWeight },
      { name: "springGreen", weight: springGreenWeight },
      { name: "mediumSpringGreen", weight: mediumSpringGreenWeight },
      { name: "brightTurquoise", weight: brightTurquoiseWeight },
      { name: "aqua", weight: aquaWeight },
      { name: "deepSkyBlue", weight: deepSkyBlueWeight },
    ];
  }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const sortedColors = colors.sort((a, b) => {
  if (a.weight < b.weight) {
    return 1;
  }
  if (a.weight > b.weight) {
    return -1;
  }
  // a must be equal to b
  return 0;