Obtain a string value from a JavaScript object

My dilemma involves a specific Javascript object.

{
    A: 1,
    B: 2,
    C: 2,
    D: 1,
    E: 1,
    F: 4,
    G: 6,
    H: 2
},

The goal is to extract a four-letter string based on the key with the highest value, but there are limitations. The string must be constructed from one of the following 16 combinations in their specified order:

A or B
C or D
E or F
G or H

This means there are only 16 possible combinations. Using the above example would yield the string "BCFG".

Has anyone come up with a solution?

Answer №1

To achieve this task, you can:

  • Extract the entries of the object,
  • Combine pairs of entries,
  • Determine which entry has a greater value,
  • Concatenate all values into a single string.
var object = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 },
    result = Object
        .entries(object)
        .reduce((r, a, i) => {
            if (i % 2) {
               r[r.length - 1].push(a);
            } else {
                r.push([a]);
            }
            return r;
        }, [])
        .map(([a, b]) => a[1] > b[1] ? a[0] : b[0])
        .join('');

console.log(result);

Answer №2

I evaluate each pair of items within the object and then create a string based on the higher value in each pair.

const obj = { A: 3, B: 4, C: 2, D: 5, E: 6, F: 3, G: 2, H: 1 } //"BDEG"

let findHighest = (obj) => {
  let result = "";
  // Transform the object into an array
  obj = Object.keys(obj).map(function(key) {
    return [key, obj[key]];
  });
  // Loop through the array with increments of 2
  for (let i = 0, len = obj.length; i < len; i += 2){
    // Compare values of two elements at a time
    if (obj[i][1] > obj[i+1][1]){
      result += obj[i][0];
    }
    else {
      result += obj[i+1][0];
    }
  }
  return result;
}

console.log(findHighest(obj));

Answer №3

var data = {
    X: 3,
    Y: 4,
    Z: 1,
    W: 5,
    P: 2,
    Q: 6,
    R: 2,
    S: 3
};

var output = Object.keys(data).reduce(function(output, item, position, list) {
  if (position % 2 === 0) {
    output.push(list[data[item] > data[list[position + 1]] ? position : position + 1])
  }
  return output;
}, []).join('');

Answer №4

let values = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 }
let characters = [];
let nums = [];
let result = "";

for (let key in values) {
    characters.push(key);
    nums.push(values[key]);
}

for (let i = 1; i < characters.length; i += 2) {
    if (nums[i-1] > nums[i]) {
        result = result + characters[i-1];
    } else {
        result = result + characters[i];
    }
}

This method provides a basic solution to the problem at hand. By organizing data into arrays and working in pairs, you can achieve the desired outcome.

While there are more complex strategies available, they may not be suitable for educational purposes ;)

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

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

Attempting to streamline the process of verifying the truthfulness of an object key and subsequently adding it to a different

In the process of creating a form to interact with a remote API, I aim to construct a GET request query string depending on which checkboxes the user chooses. Initially, I considered using a series of if/else statements to check whether the model object k ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

What could be the issue with my code? (Threejs spotlight shadow)

I recently created a Three.js scene featuring two cubes on a plane. The spotLight I placed in the top-left corner is intended to look at the coordinates 50, 0, -50. However, I noticed that the shadows appear odd and the light does not seem to be focusing ...

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Spin: twist beyond 360 degrees or less than 0 degrees

Attempting to rotate an arrow indicating wind direction using the transform: rotate() property. The data for rotation is retrieved from an API fetch, and conventional measurement of wind direction involves indicating where the wind is coming from. Therefo ...

Create basic HTML using the react.cloneElement method

When using React.cloneElement(), the first parameter always needs to be a react component that is passed as children in props. Is there a way to pass a simple HTML node as a child? Please see the example code below for clarification: Dialog.jsx (Common c ...

Enable retrieval of calculated time duration in jQuery time picker

After implementing two separate timepickers for calculating a time duration, I am looking to access this computed duration for further calculations later on the page. How can I retrieve the duration that is already displayed to the user after using the sec ...

Content in the <core-animation-pages> element is extending beyond the borders of the main DIV when the "slide-from-right" effect is applied (Polymer

Check out this quick video I made to demonstrate the issue: I have successfully incorporated core-animation-pages into my web application. I have three different divs that transition using the slide-from-right animation without any problems. However, in d ...

The website experiences a sudden crash shortly after launching, displaying the error message "EADDRINUSE" for port 80

PROBLEM I have a react-based website running on a node-express server. My backend server is working fine on port 3000, but the website on port 80 keeps crashing. When I use pm2 to start my website (https://www.edvicer.com) with the command pm2 start serv ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Change a text file into JSON by using key-value pairs or headers along with CSV in Python, JavaScript, or PHP

I have a text file with the following format. I would like to convert it to CSV with headers like in https://i.sstatic.net/WjwC7.png or as JSON key-value pairs. Any guidance would be greatly appreciated. ...

Twice the fetch is triggered

I've implemented a simple JavaScript function that handles fetching a URL and updating the HTML page upon receiving a response. Here's an example of how it works: function postToDatabase(self) { // other code here async function postData() ...

Expanding the functionality of express.Router

Can someone help me with how to extend the functionality of express.Router? I attempted the following: class Test extends express.Router() { }; However, I encountered an error when trying this in Express. Does anyone have a solution for this issue? ...

Tips for transferring information between routes in Node.js using Express.js

How can I add a specific attribute to the request object and access it from another route after redirection? Below is an example of what I am looking for: const express = require('express') const app = express() app.get('/test1',(req, ...