Sorting array of objects including negative values

Viewed 33

I have here the data

var sampleArray = [
    { "Rating 1": -75 },
    { "Rating 2": -70 },
    { "Rating 3": 98 },
    { "Rating 4": -88 },
    { "Rating 5": 29 },
  ];

I want to sort it to output the following

  1. Highest rating
  2. Lowest rating
  3. Rating that is near 0 (if there are 2 results, the positive will be chosen example:-1,1 then 1 will be chosen)

I'm stuck on getting the second value only which is the rating. I've tried the following codes to check if I can get the rating, but it shows the entire value of array 0

  function topProduct(productProfitArray) {
    return productProfitArray[0];
  }
1 Answers

You can do this with reduce and a bit of logic to keep track of your min,max and diff from zero items

var sampleArray = [
    { "Rating 1": -75 },
    { "Rating 2": -70 },
    { "Rating 3": 98 },
    { "Rating 4": -88 },
    { "Rating 5": 29 },
  ];
  
var result = sampleArray.reduce( (acc,i) => {
    var val= Object.values(i)[0];
    if(val > acc.max)
    {
       acc.maxEntry = i;
       acc.max = val;
    }
    if(val < acc.min)
    {
       acc.minEntry = i;
       acc.min = val;
    }
    var diffFromZero = Math.abs(0-val);
    if(diffFromZero < acc.diffFromZero)
    {
      acc.diffFromZero = diffFromZero;
      acc.diffEntry = i;
    }
    return acc;
},{min:Number.POSITIVE_INFINITY, max:Number.NEGATIVE_INFINITY,diffFromZero:Number.POSITIVE_INFINITY});

console.log("min",result.minEntry);
console.log("max",result.maxEntry);
console.log("closeToZero",result.diffEntry);

Related