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

What is the method for discovering all possible solutions to an NQueens puzzle when one queen is already placed in a specific column?

Have you heard about the famous NQueens problem? I have successfully implemented a program using the backtrack approach that is able to find all the solutions for a given board size. Take a look at the code snippet below. My current challenge is to modify ...

Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code: Cypress.Commands.add('login', (email, password) => { cy.get('.auth').find('.login').should(($login) => { expect($log ...

Testing API calls with ReactJS

I'm diving into Reactjs development and have encountered a challenge. I created an App that makes API calls to https://jsonplaceholder.typicode.com/users. However, when testing the API call, I ran into issues. In addition, I built a simple WebApi pro ...

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

A guide on how to assign a placeholder as the default value for a date picker

Currently using Vue3 with options API, and this question does not pertain to date formatting. Looking at the code provided on StackBlitz here, the default format for the date being initially set is dd.mm.yyyy. I am interested in knowing how to set the date ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

Utilizing Vuejs to initiate a GET request using a method

Currently, I am working on enhancing the functionality of a GET request in Vue. My goal is to attach the request sending action to the form's submit button and also include a parameter from a text field within the form. HTML <html> <head> ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

When opting for "Not now" in Firefox, the error callback in getUserMedia is not activated

I am currently working on a script to detect when the user either allows or denies the use of a microphone using the getUserMedia API. UPDATE: To better illustrate the issue I am facing, I have created a fiddle: http://jsfiddle.net/4rgRY/ navigator.getUs ...

Utilize Angular to transform items in a nested array into comma-delimited values prior to assigning them to a grid

Here is an excerpt from a JSON response retrieved from an API: { "totalCount": 2, "customAttributes": [ { "objectType": "OWNER", "atrributeId" ...

Is it possible to determine if child_process has finished in node.js?

I'm currently in the process of developing a cakefile with node.js and I need to determine whether a child_process has completed before proceeding to the next one. {exec} = require 'child_process' exec 'casperjs test.js', (err, s ...

In Reactjs, a child component is unable to activate a function that is owned by the parent

I'm working with a modal parent component and a form child component. The challenge I'm facing is that the function to open and close the modal is in the parent component, while the submit function is in the child component. What I need is for th ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

Duplicate entries in the angular-ui Calendar

I've implemented the Angular-UI calendar to showcase some events. My activity controller interacts with the backend service to fetch the data, which is then bound to the model. //activity controller $scope.events = []; Activities.get() ...

The functionality of CSS3 animations may sometimes be unreliable following the onLoad event

Here is a snippet of code to consider: $(function() { $('#item').css({ webkitTransform: 'translate(100px, 100px)' }); }); The element I am attempting to move has the following CSS properties: transform: translate3d(0 ...

Guide to extracting the key of a JSON object with a numerical name

I am having trouble extracting JSON objects from my server that contain numbered names to distinguish them. When trying to retrieve these objects, I encounter an issue with appending numbers to the common name. The structure of the objects is as follows: ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...