Arranging Array by Nearest Solution

I need help sorting an unsorted array containing calculation results:

const solution = 955

const unsortedArray =
[
  [["solution result cab"],[955.709]],
  [["solution result abc"],[951.11]],
  [["solution result cba"],[954.709]],
  [["solution result bac"],[957.709]]
]

My goal is to sort the array based on the closest deviation from the solution:

[
  [["solution result cab"],[955.709]],
  [["solution result cba"],[954.709]],
  [["solution result bac"],[957.709]],
  [["solution result abc"],[951.11]]
]

Is there a way to implement range comparison in sort(), or is there a more efficient solution?

Answer №1

To determine which element is larger based on their absolute differences from the solution, you can create a compare function. If the result is a positive number, the first element is considered bigger, while a negative result indicates that the second element is larger.

function findDifference(a, b) {
  const absDifferenceA = Math.abs(a[1][0] - solution);
  const absDifferenceB = Math.abs(b[1][0] - solution);
  return absDifferenceA - absDifferenceB;
}

After defining this function, you can use

unsortedArray.sort(findDifference)
.

Answer №2

According to the documentation on Array.prototype.sort, a sorting function can be provided as an argument:

const compareDifferenceFrom = (target) => {
  (valA, valB) => Math.abs(valA[1][0] - target) - Math.abs(valB[1][0] - target)
}

unsortedList.sort(compareDifferenceFrom(target))

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

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...

Permission error encountered during Typescript installation

I encountered an error with permissions and paths while attempting to install Typescript. Is there anyone who can help me with successfully installing Typescript? View the Typescript installation error here. ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Retain the jQuery dropdown menu in an open state while navigating to a different webpage on the

I am encountering an issue with a drop-down menu on my website. Whenever I click on a submenu link, the new page opens but the menu automatically closes. However, I want the active menu to remain open even on the new page. To solve this problem, I believe ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

How can you use yargs (npm package) to generate an error message when a command is not recognized?

Is it possible to have yargs with 2 commands? yargs .command('test-all','',handler) .command('test-file','',handler) .argv When the user inputs: node myapp.js other-command No error is thrown by yargs. What steps s ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

Using a foreach loop in PHP to retrieve the elements' index from an array

After receiving a response from the SOAP client with multiple parameters, I am struggling to display only a few of them as results. Currently, I can successfully retrieve the results for one vehicle, but I have more than one vehicle and need help looping t ...

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Header cannot be set once they have already been sent

I'm having trouble setting the header in the code snippet below. Even though I've added a return at the end of each line, the res.json(data) seems to be executing twice. Can someone please correct me if I'm mistaken? Here is the content of ...

Close the parent electron window while keeping the child window open

I am currently working on a project where I need to create an electron app that displays a splash screen initially and then opens a new window before closing the splash screen. However, despite my efforts, I am facing challenges in achieving this functio ...

A guide to crafting a fresh WordPress post with the help of the wpapi library for Node.js

After attempting to use the wpapi module to generate a post in WordPress, I encountered a puzzling issue. Despite receiving a 200 Success response, the request body was empty and no post was actually created. var wp = new WPAPI({ endpoint: 'http:/ ...

best practices for sending multiple requests using node js

I have a list of 4 URLs, each containing JSON data. How can I iterate through these URLs? Example: URLs = [ "", "", "", ""]; Each URL contains JSON data for one student as follows: { date: 08/05/2014 stude ...

Assign the textbox's value to be the earliest selected date from the datepicker

Can anyone assist me? I have a working code that activates only the specific day of the week I want on the datepicker. However, the textbox doesn't have a default value and I would like it to display the first date activated in the datepicker. In th ...

Unpredictable image sorting tool

Can someone recommend a plugin that functions similarly to the logos placement after the video section on this website: ? I really admire the way they have implemented it and would like to find something similar for my own project. ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

Steps for integrating an Angular 2 App into Express.js as a view

I am currently working on developing an Angular 2 app that requires data from a script running on the server. To achieve this, I am attempting to integrate my existing Angular app as a view within an express application, similar to the process demonstrated ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

Tips for extracting a value from a currently active list item's anchor tag with JQuery on Mapbox API?

Currently, I am attempting to extract the value from a forward geocoder that predicts addresses while a user is typing. My goal is to then send this value to a form with an id of "pickup". However, I am encountering difficulties in capturing the li > a ...