When the length of the Array is 100, the function Math.min.apply(Math, Array) will produce a

Is it okay to use Math.min.apply when the length of the Array is 10?

getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
    indexes.push(i);
}
return indexes;
}

 arrayMinIndex(array) {
return this.getAllIndexes(array, Math.min.apply(Math,array));
}

https://i.sstatic.net/917Yz.png

However, when the Array's length is larger, for example 100, the value becomes NaN.

https://i.sstatic.net/Ibzlf.png

UPDATE!!!!

If I change the index names from 00,01,02,03 ... 99 to 0,1,2,3,4 ... 99, it works fine.

https://i.sstatic.net/vQx7H.png

In this scenario, I dynamically created the Array where the index name is a String. https://i.sstatic.net/BaPUJ.png

So, why does the index name cause a problem with Math.min?

Answer №1

It appears that in the process of creating the array, keys like '01', '02' are being used

This is different from index 1 and 2

Take a look at the following example:

const array1 = new Array();
const array2 = new Array();
const array3 = new Array();
array1[0] = 1;
array2['00'] = 2
array3[0] = 3
array3['00'] = 4

console.log(JSON.stringify(array1), typeof array1[0]);
console.log(JSON.stringify(array2), typeof array2[0]);
console.log(JSON.stringify(array3), typeof array3[0]);

Notice how array2[0] is undefined ... now if you try this:

const array = new Array();
array['00'] = 10;
array['01'] = 9;
array['02'] = 8;
array['03'] = 7;
array['04'] = 6;
array['05'] = 5;
array['06'] = 4;
array['07'] = 3;
array['08'] = 2;
array['09'] = 1;
array['10'] = 100;
console.log(array);

See all those undefined values before index 10

That's why Math.min results in NaN

Answer №2

Your initial filter for non-numeric values involves checking if your array contains any non-numeric values.

var filteredArr = arr.filter(function (item) {
  return !isNaN(item);
});

To find the minimum value in the array, you can use:

Math.min.apply(Math,array.filter(n => !isNaN(n)))

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

Discovering an element within a shadow root using Selenium in conjunction with Java

Is there a way to retrieve the "Solve the challenge" button from within the shadow-root (closed) element? Here is what I've attempted so far: driver.findElement(By.xpath("//[@id=\"solver-button\"]")).click(); Unfortunately, the button canno ...

Utilizing React hooks to capture the checkbox value upon change and transfer it to the submitForm function

I've got a functioning hook that monitors the onChange event of input fields, then spreads them into a variable and sends them to a Lambda function for sending an email with SendGrid. Everything is working fine. However, when I add an input type of c ...

Is there a way to navigate to the home page using a PNG icon without refreshing the page when clicked on, while also utilizing NavLink with a route of '/'?

Here's the code I'm working with: <div key="1" className="menu-item"> <NavLink to="/"> <span className="icon-home3" />&nbsp; Home </NavLink> </div> The Home button functions ...

Track and monitor data modifications in Vue.js

I recently incorporated a Bootstrap Vue Table into my application and wanted to monitor user activity as they navigate through the pages using the pagination feature. Here is where you can find more information on the Bootstrap Vue Table To achieve this, ...

Steps for making a webpack-bundled function accessible globally

I am currently working with a webpack-bundled TypeScript file that contains a function I need to access from the global scope. Here is an example of the code: // bundled.ts import * as Excel from 'exceljs'; import { saveAs } from 'file-save ...

How can a PrivateRoute component effectively handle waiting for an asynchronous response?

I've encountered an issue with my PrivateRoute component that is supposed to verify the validity of a token. The problem lies in the fact that the validation process for rendering a view is not functioning as expected, always rendering: App.js const ...

Sliding divider across two div containers with full width

Seeking a JavaScript/jQuery function for a full page slider functionality. The HTML structure I'm working with is as follows: My objectives are twofold: Both slide1 and slide2 should occupy the full width of the page. Additionally, I am looking for ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Tips for sending an API request from a local Ionic server to a separate local Express server

I currently have two applications running on my local machine: an ionic2 app running on http://localhost:8041 and an express app running on http://localhost:8000. Using Angular 2 observables, I am encountering an issue when making API calls with absolute p ...

Guide: Initiating an action in NuxtJs

I am attempting to trigger an action in my Vue component from my Vuex store. Below is the content of my aliments.js file in the store: import Vue from 'vue'; import Vuex from 'vuex'; import axios from 'axios'; Vue.use(Vuex, ...

Using Vue.js to group JSON arrays multiple times

I have a program that I utilize to import a CSV data file and then convert it into JSON format. The resulting JSON structure is as follows: { "Class": "Cultivated Mushrooms", "Type": "Shii-take", "Grade": "Medium", "LvH": "SP", "Description": " ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

Encountering issues with JavaScript for dynamically loading content in C# ASP.NET MVC 4

I am currently working on a website project for an owner who regularly holds exhibitions. These exhibitions can be added, edited, and deleted as needed. Each exhibition is organized by year, with additional details available upon clicking the 'Read mo ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

Limiting the space character in a password field with regular expressions in JavaScript

Currently, I am facing the challenge of implementing a RegEx expression on a property within a model on an MVC website that I am currently developing. While I understand the individual components of the expression, I am struggling to combine them effectiv ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Executing mathematical operations with floating point numbers using JavaScript in Python

I’m creating a Python program that interacts with a web application that I didn’t develop. There is some data that needs to be represented in my program which isn’t directly sent to the client by the server, but is instead calculated separately on bo ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

Find and extract elements from a nested array within an object inside another object within an array of objects

I am working with an array of objects that looks like this: [ { likes: [], _id: 5f254e21fd3e040640de38b2, content: 'try this', author: { posts: [Array], comments: [], images: [], followers: [Array], ...