What is the best way to find the index of the smallest value in an array using JavaScript?

I recently created this function that currently outputs -1.

function sayHello() {
  let buildingLevelsArray = [11,10,10];
  var smallestIndex = buildingLevelsArray.indexOf(Math.max(buildingLevelsArray));
  console.log(smallestIndex);
}
sayHello();

Instead of -1, I was expecting it to be 0. Any suggestions on how to fix this issue?

Answer №1

You must ensure that the array is spread out to obtain the maximum value. Otherwise, if you try to access it directly as a stringed array, you will get NaN, which is not part of the array and cannot be searched.

When you spread the array, all its elements are used as parameters for the function (see spread syntax ...).

In this scenario, the operation looks like this:

Math.max(...[11, 10, 10])

will be computed as

Math.max(11, 10, 10)

function sayHello() {
  arrayEdificiosNiveis = [11, 10, 10];
  var indexMenor = arrayEdificiosNiveis.indexOf(Math.max(...arrayEdificiosNiveis));
  
  console.log(indexMenor);
}

sayHello();

A concise solution using a single loop:

However, why not utilize

v > a[r] ? i : r

(which seems more intuitive) instead of

v <= a[r] ? r : i

The issue arises from the initial comparison with the element at index zero. At that point, r = -1 and the element is a[r] = undefined.

Comparing with undefined using a relational operator such as <, <=, >, or >= always returns

false</code, resulting in the incorrect index of <code>-1
instead of zero. This error persists for every other element in the array.

const
    getFirstIndexOfMaxValue = array =>
        array.reduce((r, v, i, a) => v <= a[r] ? r : i, -1);            

console.log(getFirstIndexOfMaxValue([]));
console.log(getFirstIndexOfMaxValue([11]));
console.log(getFirstIndexOfMaxValue([11, 10]));
console.log(getFirstIndexOfMaxValue([11, 10, 10]));
console.log(getFirstIndexOfMaxValue([10, 11, 10]));
console.log(getFirstIndexOfMaxValue([10, 11, 10, 11]));

Answer №2

The issue with the method you are using lies in the array that is being passed to the Math.max function:

const buildingLevelsArray = [11, 10, 10],
  maxLevel = Math.max(...buildingLevelsArray);
  
console.log(buildingLevelsArray.findIndex(elem => elem === maxLevel);

If you are unable to utilize the Spread syntax, an alternative approach is to use the apply function with an array as parameters for the Math.max function.

function findMax() {
  const buildingLevelsArray = [11, 10, 10],
    maxLevel = Math.max.apply(null, buildingLevelsArray),
    indexOfMax = buildingLevelsArray.indexOf(maxLevel);
  console.log(indexOfMax);
}
findMax();

Answer №3

For expert advice, consider reaching out to Raymond Chen. Interestingly enough, the straightforward C-style approach reigns supreme in this scenario. It's not surprising that Javascript engines find C style code easy to optimize.

function findIndexOfSmallestValue(arr) {
 var lowestIndex = 0;
 for (var j = 1; j < arr.length; j++) {
  if (arr[j] < arr[lowestIndex]) lowestIndex = j;
 }
 return lowestIndex;
}

Answer №4

const numbers = [-1, 5, -4, 7, 10, 2, 9, 6, 8];
let output = "";
let finalOutput = "";
let index = 0;

while (index <= numbers.length) {
    index++;
    let tempNum = numbers[0];
    let nextNum = numbers[index];

    if (tempNum === nextNum) {
        finalOutput = tempNum;
        output = nextNum;
    } else if (tempNum > nextNum) {
        output = nextNum;
    } else if (output < tempNum) {
        finalOutput = output;
    }
}

if (finalOutput < output) {
    console.log(finalOutput);
} else {
    console.log(output);
}

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

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

What is the best way to incorporate a range of details into a div using only jQuery, all while avoiding the use of data-

I'm struggling to find a concise way to explain this, so please bear with me. The information I'm sharing here is all just for example purposes and may sound strange. I have been working on creating a character select page where clicking on a cha ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

¿What is preventing me from merging two arrays within this query handler?

I'm facing an issue while trying to merge arrays from a request with existing arrays in a MongoDB database. Despite my attempts, the arrays do not seem to be merging as expected. Can anyone help me identify what might be causing this problem? router.p ...

Generating a USA map with DataMaps in d3jsonData

I'm trying to create a basic US map using the DataMaps package and d3 library. Here's what I have attempted so far: <!DOCTYPE html> <html> <head> <title> TEST </title> <script src="https://d3js.org/d3.v5.js"> ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Learn how to effectively declare data as global within Angular2 or Typescript

I am facing an issue with fetching the id inside the Apiservice despite being able to get it in the console. Can anyone provide assistance on how to solve this problem? TS: deleteProduct(index,product) { var token = this.auth.getAccessTokenId(); ...

Trouble with Bootstrap Collapse feature not collapsing on its own

I recently added a Bootstrap collapse feature to my payment view in Laravel. The Bootstrap section collapses when clicked, but I would like it to be collapsed by default. I understand that I need to include: aria-expanded="false" However, it still doesn& ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

What is the most efficient method for identifying and modifying an element's in-line style while performing a swipe gesture?

Recently, I've been developing a left swipe gesture handler for chat bubbles. Implementing touchMove and touchStart seems like the logical next step, but for now, I'm focusing on making it work seamlessly for PC/web users. I managed to make it f ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Error: Attempting to access index '0' of an undefined property in firebase and vuex

When using a vuex action to upload an image to Firebase and save the URL, everything seems fine until trying to retrieve the downloadUrl and adding it to the meetup database reference. The code I have looks like this: actions: { createMeetup ({commit ...

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...

Having difficulty applying a style to the <md-app-content> component in Vue

Having trouble applying the CSS property overflow:hidden to <md-app-content>...</md-app-content>. This is the section of code causing issues: <md-app-content id="main-containter-krishna" md-tag="div"> <Visualiser /> </md-app ...

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

What is the best way to use scrollIntoView() to display an additional item at the top or bottom of the visible area

When implementing scrollIntoView() with navigation buttons (up and down), I aim to display two items at a time to signal to the user that there are more items to navigate. However, the first and last items should retain their default behavior so the user u ...

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...