Arranging an array of objects that contain negative numbers

Here is the dataset provided

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

I am looking to organize it in the following manner

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

My challenge lies in extracting only the second value which represents the rating. I have attempted various codes but so far, I am only able to retrieve the entire value of array 0

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

Answer №1

To achieve this task, you can utilize the `reduce` method along with some conditional statements to keep track of the minimum, maximum, and items closest to zero in an array.

var data = [
    { "Value A": -52 },
    { "Value B": 78 },
    { "Value C": -14 },
    { "Value D": 92 },
    { "Value E": -20 },
  ];
  
var output = data.reduce( (acc,item) => {
    var value= Object.values(item)[0];
    if(value > acc.max)
    {
       acc.maxEntry = item;
       acc.max = value;
    }
    if(value < acc.min)
    {
       acc.minEntry = item;
       acc.min = value;
    }
    var diffFromZero = Math.abs(0-value);
    if(diffFromZero < acc.diffFromZero)
    {
      acc.diffFromZero = diffFromZero;
      acc.closestToZero = item;
    }
    return acc;
},{min:Number.POSITIVE_INFINITY, max:Number.NEGATIVE_INFINITY,diffFromZero:Number.POSITIVE_INFINITY});

console.log("Minimum:",output.minEntry);
console.log("Maximum:",output.maxEntry);
console.log("Closest To Zero:",output.closestToZero);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an Unexpected Token "h" with DynamoDB and Node.js Integration

Currently, I am attempting to follow the Node.js Amazon start guide with DynamoDB. My goal is to create a table, but unfortunately, I am encountering an error: Unable to create table. Error JSON: { "message": "Unexpected token h", "code": "SyntaxError ...

Tips for displaying a div near the cursor's location when hovering in React JS

Looking for a way to show a hidden div at cursor position when hovering on Text item1 or item2. Check out the sample GIF animation in this Link My attempt using Jquery code inside React resulted in an error: $(".text-item").mouseenter(function ( ...

Is it possible to switch classes when hovering?

Here is the code I have created: $(document).ready(function () { $("#rade_img_map_1335199662212").hover(function () { $("li#rs1").addClass("active"); //Adding the active class when area is hovered }, function () { $("li#rs1").addC ...

Javascript Fetch Producing Varying Results

My React Native app is being tested using Expo Go. I am making a request to fetch data from a website using the Fetch API. The first time I fetch the data, it sometimes returns {"next": null, "parent": {"children": [[Circular] ...

What is the best way to position text both before and after the alert box is displayed?

Seeking guidance as a newbie in Javascript. I would like to allow the user to input their name into a text box and upon submitting it, display an alert saying "hello" followed by the user's name. The code currently outputs the user's name in an a ...

Press on the thumbnails in the gallery slider to activate links to external thumbnail images

I am looking to activate both the .main and .thumb links by clicking either one of them. //The following code activates both .main and .thumb when the .main link is clicked. $(".main a").on("click", function(){ var target= $(this).attr("href"); ...

Transform a flat JSON string into a hierarchical structure by organizing it by parent ID

I am currently working on implementing a Mat-Tree using Angular Material. The data I have is in the form of a flat JSON string: "Entity": [ { "ID": 1, "NAME": "Reports", "PARENTID": "0", "ISACTIVE": "Y", "CREATIONDATE": "20 ...

Reducing the key in MongoDB to a single value

I am trying to create a MapReduce program that counts the number of orders by clients within the last year, month, and week. var mapOrders = function() { var v_order = { order_date : this.dt_order ... }; emit(this.clientid, ...

What is the best way to execute NPM commands within the terminal of Visual Studio Code?

I recently installed npm in VSCode from extensions, but I am having trouble activating it. When I try to run the command 'npm init' in the terminal, I receive the following error message: "The term 'npm' is not recognized as the name of ...

What is the best way to adjust for a container view that has been rotated within my circular slider component?

After combining different code snippets, I have successfully created a circular slider component that functions as a slideable control dial with a defined maximum angle. However, I am now seeking more flexibility by wanting to specify a custom start angle. ...

Optimal method for storing and retrieving JSON data in Laravel using a database

Attempting to save JSON data into a database and retrieve it. I successfully saved the following: {name: "John", age: 31, city: "New York"} It stored correctly in the database and displayed properly when checked. {name: "John&q ...

encountering a typeError upon attempting deployment on Heroku

This is my first project using node.js, so my code may not be perfect It runs smoothly on my localhost, but on Heroku, I encounter an 'Internal Server Error' along with a TypeError. I apologize for my limited knowledge of node.js and ejs, but I ...

Decide on the javascript/jquery libraries you want to include

My app is experiencing slow loading times on the home screen and students using it from school district computers are running into ERR_CONNECTION_RESET errors due to strict firewalls. The excessive loading of javascript and jquery libraries in the head of ...

Is there a way to prevent Chrome from automatically toggling into debug mode?

When the debugging window is open, the debugger seems to start running through lines automatically without any breakpoints being set. I attempted to use the "Deactivate breakpoints" button, but it had no effect whether it was enabled or disabled. This is ...

Ways to develop a dynamic HTML TransferBox featuring a custom attribute

I am in need of developing a customized transferbox using HTML, JavaScript, and JQuery. The user should be able to select from a list of options and associate them with attributes. This selection process should involve transferring the selected options be ...

Unable to retrieve route parameters in Angular 2

I have a scenario similar to this <a [routerLink]=" ['../projects', project.id] "> However, when attempting to retrieve a route parameter from the URL, I am not getting any results. Here is my import: import { Component} from '@ang ...

Exploring the power of Cucumber, Ruby, Capybara, and Selenium: Enhancing the 'visit' method to handle dynamic content delays

For weeks now, I've been dealing with an issue that seems to have no solution found online... like waiting for ajax, etc... Check out the versions of gems: capybara (2.10.1, 2.7.1) selenium-webdriver (3.0.1, 3.0.0) rspec (3.5.0) running ruby 2.2.5 ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...

The div is inexplicably shifting downward once the first three rows are shown correctly

After displaying the first 3 rows properly, the div mysteriously moves down. Could I be making a silly mistake? All images have the same width and height. Please see the attached image for reference. <?php // start first row echo "<hr class='m ...