Finding the position of the biggest floating point number in the array

What is the best way to find the index of the largest element in an array of floating point numbers?

[0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8]

Once the index of the largest element is determined, the goal is to retrieve the corresponding value from another array.

For illustration purposes, let's refer to the second array as:

['a', 'b', 'c', 'd', 'e']

After running some code, the result was 'b' instead of 'c'.

An attempt was made to map the floats to their corresponding strings in the second array. Then the string at the index of the smallest float in the sorted array was retrieved.

// aInput contains the array of floats
var emObj = {};
for(var i=0; i<aInput.length; i++){
    emObj[aInput[i]] = ['a', 'b', 'c', 'd', 'e'][i];
}
return emObj[aInput.sort()[0]];

Another approach involved iterating through the array of floats to identify the largest value, and then using that value to retrieve the corresponding string.

return ['a', 'b', 'c', 'd', 'e'][aInput.indexOf(largestFloat)];

Unfortunately, neither of these methods produced the desired outcome, consistently returning an incorrect string.

Answer №1

If you're looking for a solution, I recommend utilizing Math.max() along with indexOf()

let maximumNumber = Math.max.apply(null, inputArray);
let position = inputArray.indexOf(maximumNumber);
return ['apple', 'banana', 'cherry', 'date', 'elderberry'][position];

Answer №2

A method utilizing the Array.prototype.reduce() function

This approach allows for intricate logic within the reduce process.

To begin, establish some initial data:

var numbers = [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8];
var letters = ['a', 'b', 'c', 'd', 'e'];

Next, determine the maximum value and its index within the array.

var maxResult = numbers.reduce(function (prevValue, currValue, index, arr) {
  if(prevValue.val > currValue) {
    return prevValue;
  } else {
    return {val: currValue, idx: index};
  }
})
console.log(letters[maxResult.idx]);

Alternatively, you can directly retrieve the corresponding value like so.

var result = numbers.reduce(function (prevVal, currVal, index, arr) {
  if(prevVal.val1 > currVal) {
    return prevVal;
  } else {
    return {val1: currVal, val2: letters[index]};
  }
})
console.log(result);

The result displayed is

Object {val1: 0.9573732678543363, val2: "c"}

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

What is the best way to bind data to a textarea component and keep it updated?

I started using VueJS just a week ago for a new project. During this time, I have successfully created two components: * Account.vue (Parent) <!--This snippet is just a small part of the code--> <e-textarea title="Additional Information" ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

Encountering a Typescript error while attempting to iterate through Enum keys for generating JSX components

I'm really struggling with this problem. Here's a simple enum I have: export enum depositTypes { ACH = 42, Wire = 36, Check = 3, Credit = 2, } I'm trying to create option tags for a select element, like so: Object.keys(depositTyp ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

Authentication through Proxy and requests from nodes

I am attempting to make a get request to a website via https using the request module. However, I am behind a proxy that requires authentication. Despite my attempts to add the authentication, the connection to the site fails. I have experimented with add ...

Adding a <tr> tag to an HTML table using JQuery and AJAX in the context of Django framework step by step

I am currently navigating the world of Javascript, Jquery, and Ajax requests and I'm encountering a challenge with how my scripts are executing. My homepage contains a lengthy list of items (over 1200) that need to be displayed. Previously, I loaded ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Storing information from a table into LocalStorage

$('.new_customer').click(function () { var table = $("table"); var number = table.find('tr').length; table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" ...

React does not accept objects as valid children. If you want to render a group of children, make sure to use an array instead

I am in the process of developing a system for document verification using ReactJS and solidity smart contract. My goal is to showcase the outcome of the get().call() method from my smart contract on the frontend, either through a popup or simply as text d ...

Javascript is unable to locate the clientid

Encountering an error message like the following: 'System.Web.UI.WebControls.TextBox' doesn't have a definition for 'ClentID' and there isn't any extension method 'ClentID' that accepts the first argument of type &a ...

Ways to have a list component smoothly descend when a dropdown menu is activated

I have a situation where I have a list with two buttons, and each button triggers the same dropdown content in a sidebar component. The issue is that when I click on one button to open the dropdown, the second button does not move down to make space for it ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Using Angular to invoke the transclude directive function inside the transcluded component

I am looking to develop a component that includes a transcluded section, take a look at this example: http://jsfiddle.net/vp2dnj65/1/ Upon clicking the "do" button in the example, nothing seems to happen. Is there a way to execute the transcluded cont ...

Encountering the error code [$injector:unpr] regarding an unknown provider: $uibModalInstanceProvider

In my web application, I have a controller called AddPrice. This controller is invoked from a Price listing screen as a popup using the $uibModal.open method, where the controller is passed in as an argument. However, the controller is not defined within t ...

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

Creating a Java array without specifying the size in advance

Is there a way to create an array of objects from a class within another class without specifying the size in advance? ...

What is the process for updating the h1 header with text entered into an input field?

I'm working on an assignment that requires me to change the h1 heading to reflect whatever is entered into the input field. To accomplish this, I need to create a function using getElementByID. Here's what I've done so far: <!DOCTYPE htm ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...