What is the process for isolating variables from an array depending on their specific values?

I have a collection of variables stored in an array. My goal now is to identify and extract the variables with the highest values, then store them in a separate array.

This task pertains to a JavaScript program that I am developing for my daughter's Wix website.

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}],

Since the variables are already arranged in ascending order based on their values, the program needs to identify ties at the top position (such as mistral, saya, and luna), extract these variables along with their respective values, and save them in a new array. In cases where only one variable has the highest value, that single variable will be stored in the new array.

Answer №1

To extract the largest value from an array of objects, we can utilize a combination of .map and .reduce functions for efficient processing. By identifying the maximum value first, we can then isolate the objects in the points array that match this value based on their first properties, subsequently storing them in a separate array named newArray.

var maxValue = points
    .map(function(obj){ return obj[Object.keys(obj)[0]]; }) //extract numbers into an array
    .reduce(function(a, b){ return Math.max(a, b);}); //determine the maximum value

var newArray = points // filter objects with first property equal to maxValue
    .filter(function(obj){ return obj[Object.keys(obj)[0]] === maxValue; });

The output will display:

[{mistral: 4}, {saya: 4}, {luna: 4}]

Answer №2

If your array is sorted, finding the maximum value is easy because it will be at the last position. You can simply retrieve this value and then filter out elements that match it:

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}];

// Since the array is ordered, the highest value is at the last position.
// Retrieve it like this:
let maxVal = Object.values(points[points.length - 1])[0];
console.log(maxVal);

// Now, filter the array to find elements matching the highest value
let highest = points.filter(x => Object.values(x)[0] === maxVal);
console.log(highest)

If your initial array is not sorted as mentioned, you can still find the highest value using a different approach:

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{saya}, {rodeo}, {mistral}, {balthazar}, {luna}, {kiara}, {calypso}];

// In case the array is not ordered, find the highest value.
// Obtain it like this:
let maxVal = points.reduce((max, v) => Math.max(Object.values(v)[0], max), null);
console.log(maxVal);

// Filter the array for elements matching the highest value
let highest = points.filter(x => Object.values(x)[0] === maxVal);
console.log(highest)

Answer №3

Check out this ES6 approach to solving the problem. It handles the scenario where the list is not in order, allowing the highest values to be situated anywhere within the list. Additionally, you can tweak the code to retrieve the smallest values if needed. Feel free to reach out with any queries about the code, and I'll provide assistance promptly.

const kiara = 1;
const rodeo = 3;
const calypso = 3;
const balthazar = 3;
const mistral = 4;
const saya = 4;
const luna = 4;


function getNamesWithHighestPoints(points) {
  const hash = {};

  for(let i = 0; i < points.length; i++) {

    let point = points[i];
    let name = Object.keys(point)[0];
    let score = Object.values(point)[0];

    if(hash[score] === undefined) {
      hash[score] = [point];
    }
    else {
      hash[score].push(point);
    }
  }

  let biggestScore = 0;
  Object.keys(hash).forEach(pointKey => {
    if(biggestScore < pointKey) {
      biggestScore = pointKey;
    }
  });
  return hash[biggestScore];
}
const points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}];

console.log(getNamesWithHighestPoints(points));

Answer №4

Here is a simple solution that can be accomplished with minimal code. When dealing with objects, utilizing for-in loops can simplify your workflow.

var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;

var points = [{rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna},{kiara}];

var maxNumberArray = [];
var maxNamesArray = []; // New line added for storing names
var max;

for(var char in points){
    for(var name in points[char]){
        if(!max){
            max = points[char][name];
        } else {
            if(max < points[char][name]){
                max = points[char][name];
            }
        }
    }
}

for(var char in points){
    for(var name in points[char]){
        if(points[char][name] === max){
            maxNumberArray.push(points[char]);
            maxNamesArray.push(name); // Additional line to store names
        }
    }
}

console.log(JSON.stringify(maxNumberArray));
console.log(maxNamesArray); // Displaying names of maximum elements as well

:)

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

Modify the background of a div and an image

My goal is to add a background to both the image and the div itself, similar to what I've seen on Amazon. However, I'm struggling to achieve this effect where the white background of the image doesn't show when applied onto the div: Image w ...

The visual representation is not being generated (three.js)

I recently designed a basic scene in three.js, however I am facing an issue where it does not seem to work with the canvas renderer, even though it should work correctly. Here is the code: http://jsfiddle.net/PRkcJ/ The scene only functions properly when ...

What strategies can I use to optimize an eval loop in JavaScript?

Upon taking over a codebase, I was greeted with this particular coding style devoid of any tests: var series1 = []; var series2 = []; var series3 = []; var series4 = []; var series5 = []; var series6 = []; var series7 = []; var series8 = [ ...

Divide HTML elements every two words

Can you use CSS to break up HTML content after every 2 words, ensuring it works for any word combination? Example: // Original HTML content The cat is sleeping // Desired result: The cat is sleeping ...

VBScript - Retrieve a Recordset as an Array (SQL-Like Feature)

I am currently developing a program to assist the accountant at my company. I am encountering an issue with returning articles' families in an array where each family must have an accounting code that starts with "707". Below is the VBScript code I ha ...

Is it acceptable to include multiple modules within a single JavaScript file?

One thing that I've noticed is that the AngularJS (*.js) files I've come across typically only have one module, and the module name doesn't always match the file name. I'm curious to know if it's possible to include multiple modul ...

Uploading Files Using JSON with Javascript and Jquery

I need to create an HTML list with a single li element named import. Behind it, there should be an input type ="file" that is initially hidden. When the user clicks on import, it should trigger the file upload from the hidden input field using .click(). ...

What is the method to display the Vue.js component's identifier?

Here is a link to an official document: https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Component Below is a demonstration of a simple todo list: Vue.component('todo-item', { template: '\ <li>\ {{ titl ...

Creating a countdown timer that is determined by the word count of a specific <div> element

What I have: A unique countdown timer that starts at 3 seconds and counts down to 0s. <div class="phrase"> This is a statement.</div> <p> <div style='font-family: Arial; font-size: 12px; color:gray'> <br><s ...

Proceed with another ajax request only when the previous one has been successfully completed and loaded

While scrolling down and loading content into my page, I am facing an issue. The ajax executions load too quickly, causing the subsequent calls to not receive correct information from the first ajax call that is loaded into the DOM. How can I ensure that ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

Sending a JSON object as a map through AJAX to an MVC controller

I am looking to send a map (dictionary) to the MVC controller along with a string parameter. var reportName= 'ReportName'; var FilterValues = new Map([ [0, "value1"], [1, "value2"], [2, "value3"], ]); var model = { reportName: reportName, ...

What is the best way to imitate the action of clicking a hyperlink?

Let's imagine that we have two links, a1 and a2, where a2 is currently hidden from view. Is there a way in jQuery to make it so that when a user clicks on link a1, it triggers the same action as clicking on link a2? ...

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

Best practice in AngularJS: Conceal/unveil fresh DOM elements or compile

Just starting out with AngularJS and looking to adjust button behavior on the fly. Coming from a JQuery background, I'm used to using element.attr('ng-click', 'controller.function()'). However, it seems that AngularJS requires co ...

In JavaScript, you can use regular expressions to group the characters `**` along with the

If I want to use JavaScript RegExp to match an expression string, how can I do it effectively? For example: '1**2*3+4' -> ['1', '**', '2', '*', '3', '+', '4'], rather than ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

Unable to access UI application login through browser using SSH tunnel on Putty

After successfully setting up an SSH tunnel using putty from my local Windows to a remote Linux server, I was able to access localhost:8080 in my Chrome browser and confirm that the SSH tunnel is functioning as it displayed my UI from the remote machine. ...

Retrieve the property by mapping the click event

I am looking for a way to retrieve the ID of a specific item when a link button inside a mapped list is clicked. How can I achieve this functionality? idFinder(){ console.log('ID:', item.id); } this.sampleData = this.state.data.map((item, ...

Getting the selection within a particular div – how can it be done?

Currently, I am working on a contenteditable div feature (identified by id 'editor1') which allows users to input text. Additionally, there is a function that enables users to highlight and change the color of selected text. In my JavaScript code ...