Exploring Javascript's Standard Object: A Guide to Retrieving Two Elements

If I have a special data object:


 var data = [];

 data["Name"] = ["Janet", "James", "Jean", "Joe", "John"];
 data["Number"] = [25, 22, 37, 19, 40];

Let's say I'm looking for the minimum number value, which is '19' in this case.

How can I retrieve and display the Name associated with this minimum number value? And how about the Name associated with the maximum value?

Is there a way to return two elements simultaneously and determine if they are related to each other?

I attempted using indexOf(), but it seems methods like that don't work as expected on Standard Objects. I am still learning Javascript, so any help would be greatly appreciated.

EDITED: Just realized I forgot to put square brackets around the arrays...

Answer №1

Utilize the Math.max.apply method to retrieve the largest value from the array, and employ Array#indexOf to obtain the index of the largest number

var data = {}; //Initialize it as object

data["Name"] = ["Janet", "James", "Jean", "Joe", "John"];
data["Number"] = [25, 22, 37, 19, 40];

var max = Math.max.apply(null, data["Number"]);
console.log(max);
console.log(data["Name"][data["Number"].indexOf(max)]);
//-----------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^To get the index of largest number

Answer №2

Here is an alternate solution that utilizes the ES6 Array.prototype.find() method:

// Finding the maximum number
var index = data["Number"].indexOf(Math.max.apply(null, data["Number"])),
    nameWithMax = data["Name"].find((value, i) => i === index);
console.log(nameWithMax);  // Outputs "John"

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 are the steps to calculate the sum and product of values extracted from TextViews within a ListView, and then showcase the results

I am a beginner in programming and I could use some help with this task. I have an Activity that contains a button and a listview. The listview displays values such as name, price, category, and quantity, which are defined through an adapter. I am trying t ...

Using jQuery, Ajax, and HTML together can create dynamic

Is there a way to run JavaScript functions in an HTML file that is loaded using AJAX? The HTML file contains both text and JavaScript, but only the inline JavaScript seems to work (like onclick="dosomething();return false"). The pre-defined functions wra ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Retrieve information from child components and populate form fields

Currently, I am working on creating a dynamic form that utilizes a sub component to display input fields because creating them statically would exceed a limit. I pass the states for the form I created along with some data and the change form function. Howe ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

Exploring ways to check async calls within a React functional component

I have a functional component that utilizes the SpecialistsListService to call an API via Axios. I am struggling to test the async function getSpecialistsList and useEffect functions within this component. When using a class component, I would simply cal ...

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

Efficiently handle user authentication for various user types in express.js with the help of passport.js

Struggling to effectively manage user states using Passport.js in Express.js 4.x. I currently have three different user collections stored in my mongodb database: 1. Member (with a profile page) 2. Operator (access to a dashboard) 3. Admin (backend privi ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

Tips for applying a jQuery class when the page is both scrolled and clicked

As I work on building a HTML website, I encountered an interesting challenge. I want to create a dynamic feature where, as users scroll through the page, certain sections are highlighted in the navigation menu based on their view. While I have managed to a ...

Unable to delete element from the given array

I have been working on removing instances of 'store.state.location.locations' from my locationData array that should no longer be there, but for some reason, they are persisting in the array even though I am no longer passing those instances. ta ...

Having trouble accessing the information stored in the Firebase Database?

As a newcomer to Firebase and JS, I am attempting to showcase user information on a webpage that is stored within the Firebase database. The data format resembles the image linked here I have written this Javascript code based on various tutorials. Howev ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Creating a Multidimensional Dynamic Array: A Step-by-Step Guide

I'm new to MQL4 coding and currently working on my first EA. I've recently discovered Arrays and now I'm interested in coding a Multidimensional Dynamic Array. My goal is to analyze the past 100 bars, identify the highest 50 bars, save and l ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

Discover the technique for splitting a string using jQuery with multiple strings as separators

I am looking to split a string in jQuery or JavaScript using multiple separators. When we have one string as a separator, our code looks like this: var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981"; var pieces = x.split("\n"), p ...