Utilizing a JSON array to determine optimal timing according to user preferences

In my pursuit to find the optimal performance for each user from a JSON dataset.

const users = [
    {
        "key": "user1",
        "label": "Henry"
    },
    {
        "key": "user2",
        "label": "Michael"
    },
    {
        "key": "user3",
        "label": "Fiddel"
    },
    // Additional user data...
]

const results = [
    {
        "user1": "00:31.241",
        "user2": "00:30.945",
        // Additional result data...
    },
    // Additional sets of results...
]

My current solution involves:

let array = [];
 
const bestTime = results.map(Object.entries).flat().sort((a, b) => a[1] ?.localeCompare(b[1]))[0];

array = [users.filter(user => user.key === test[0])[0].label, test[1]]

The challenge lies in displaying an array containing the best result for every user, not just one. Desired output format: [{name: 'Henry', value: 00:35.233}, {name: 'Michael', value: 00.27.333}, etc]

Currently, I am attempting to calculate the total sum of values for each user, filtering out null entries and computing the sum. However, as the values are stored as strings, converting them to integers for accurate calculation is proving to be a hurdle.

const final = users.map(({ label, key }) => ({

    name: label,
    value: results.map(r => r[key]).filter(el => el != null).reduce((prev, curr) => parseInt(prev) + parseInt(prev));


}));

Answer №1

Begin by iterating through the results and merging each user# property value into an array for that specific user. Then, sort the values, establish an object linking user#s to names, and extract the first value from the sorted array to acquire your desired result:

const users=[{key:"user1",label:"Henry"},{key:"user2",label:"Michael"},{key:"user3",label:"Fiddel"},{key:"user4",label:"Alex"},{key:"user5",label:"Inga"}],results=[{user1:"00:31.241",user2:"00:30.945",user3:"00:33.065",user4:null,user5:null},{user1:"00:28.963",user2:"00:31.657",user3:"00:28.504",user4:null,user5:null},{user1:"00:26.956",user2:"00:26.416",user3:"00:27.328",user4:"00:29.904",user5:null},{user1:"00:31.889",user2:"00:32.739",user3:"01:00.515",user4:"00...

const timesByUserNumber = {};
for (const result of results) {
  for (const [userNumber, time] of Object.entries(result)) {
    if (!timesByUserNumber[userNumber]) {
      timesByUserNumber[userNumber] = [];
    }
    if (time) {
      // Exclude nulls:
      timesByUserNumber[userNumber].push(time);
    }
  }
}
for (const arr of Object.values(timesByUserNumber)) {
  arr.sort((a, b) => a.localeCompare(b));
}
const userLabelsByUserNumber = Object.fromEntries(
  users.map(({ key, label }) => [key, label])
);
const output = Object.entries(timesByUserNumber)
  .map(([userNumber, timeArr]) => ({
    name: userLabelsByUserNumber[userNumber],
    value: timeArr[0]
  }));
console.log(output);

You can also "sort" by individually comparing each item while going through:

const users=[{key:"user1",label:"Henry"},{key:"user2",label:"Michael"},{key:"user3",label:"Fiddel"},{key:"user4",label:"Alex"},{key:"user5",label:"Inga"}],results=[{user1:"00:31.241",user2:"00:30.945",user3:"00:33.065",user4:null,user5:null},{user1:"00:28.963",user2:"00:31.657",user3:"00:28.504",user4:null,user5:null},{user1:"00:26.956",user2:"00:26.416",user3:"00:27.328",user4:"00:29.904",user5:null},{user1:"00:31.889",user2:"00:32.739",user3:"01:00.515",user4:"00...

const userLabelsByUserNumber = Object.fromEntries(
  users.map(({ key, label }) => [key, label])
);
const grouped = {};
for (const result of results) {
  for (const [userNumber, time] of Object.entries(result)) {
    if (!time) continue;
    const name = userLabelsByUserNumber[userNumber];
    if (!grouped[name]) {
      grouped[name] = { name, value: time };
    } else if (grouped[name].value.localeCompare(time) > 0) {
      grouped[name].value = time;
    }
  }
}
console.log(Object.values(grouped));

Answer №2

To find the best times, I came up with a solution that involved sorting the time values using the .localeCompare() method and extracting the first element from the result array. Afterwards, I applied .map() to the results array and listed the times based on their key properties within another nested .map() for each user.

Below is a demonstration of how this works:

const users = [{"key": "user1","label": "Henry"},{"key": "user2","label":"Michael"},{"key": "user3","label": "Fiddel"},{"key": "user4","label": "Alex"},{"key": "user5","label": "Inga"}]
const results = [{"user1": "00:31.241","user2": "00:30.945","user3": "00:33.065","user4": null,"user5": null},{"user1": "00:28.963","user2": "00:31.657","user3": "00:28.504","user4": null,"user5": null},{"user1": "00:26.956","user2": "00:26.416","user3": "00:27.328","user4": "00:29.904","user5": null},{"user1": "00:31.889","user2": "00:32.739","user3": "01:00.515","user4": "00:28.336","user5": "00:35.745"},{"user1": "00:26.470","user2": "00:30.063","user3": "00:28.696","user4": "00:30.248","user5": "00:35.123"},{"user1": "00:26.956","user2": "00:33.588","user3": "00:30.021","user4": "00:29.154","user5": "00:38.492"},{"user1": "00:27.190","user2": "00:32.307","user3": "00:30.467","user4": "00:30.189","user5": "00:39.669"},{"user1": "00:27.368","user2": "00:28.124","user3": "00:29.960","user4": "00:29.649","user5": "00:42.450"},{"user1": "00:28.429","user2": "00:27.651","user3": "00:28.260","user4": "00:30.077","user5": "00:48.992"}, {"user1": "00:29.425","user2": "00:31.142","user3": "00:40.343","user4": "00:29.897","user5": "00:42.552"}]
    
const bestTimes = users.map(({label, key}) => ({
   name: label,
   value: results.map(r => r[key])
                 .sort((a, b) => 
                     a === null && b === null ?
                       -1 :
                       a.localeCompare(b))[0]
}))

console.log(bestTimes)

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

Implementing multiple content changes in a span using javascript

Having an issue with a pause button where the icon should change on click between play and pause icons. Initially, the first click successfully changes the icon from a play arrow to a pause icon, but it only changes once. It seems like the else part of the ...

Promise disregards the window being open

I'm facing an issue with redirecting users to Twitter using window.open in a specific function. It seems like the instruction is being ignored, even though it works perfectly on other pages. Any ideas on how to fix this? answerQuestion() { if ...

Running jQuery scripts through PHP

$("#bt-potrdi").click( function(e) { e.stopPropagation(); $("#belina").css({"z-index":200}); $("body").addClass("ext"); $("#vpisok_frame").css({"z-index":250}).fadeIn(200); }); Upon clicking the button, the ...

Why was the express.js boilerplate code created?

As a newcomer to Node and Express, I am curious about the purpose of the boilerplate directories that are automatically generated when setting up an express project. I have searched online for explanations on the significance of these files without much l ...

Deconstructing and processing nested JSON objects on iOS

I've been dealing with nested JSON objects in iOS, but I'm having trouble parsing them. Can anyone lend a hand? I've tried several sources, but none have been helpful. The JSON file looks like this: { "taskList":[ { "taskId":1 ...

What is the method for retrieving array input data with jQuery?

Here is an example of my input field: <input type="hidden" name="data[{{ $parentIndex }}][{{ $index }}]" value="{{ $value }}"> Sample data provided below: <input type="hidden" name="data[0][0]" ...

Refresh the jQuery Carousel when the window is resized to switch the orientation from vertical to horizontal

I am in the process of creating a gallery for a responsive layout, utilizing jQuery Riding Carousels for the thumbnails. You can find more information about it here. One issue I am encountering is that when the window size shrinks to be smaller than 1024p ...

Transferring data from AJAX form in JavaScript to PHP function

My website features a login form that sends data, such as email address, to a PHP function and initiates the creation of a user. I am looking to include additional information on the page where the form is located. Here is the data I want to include in t ...

Images, videos, and audios fail to load on Vercel

I created a quirky Vercel app that poses a 'yes or no' question: "Do you want to see my dog?" If the answer is yes, my dog will appear with a woof audio; if the answer is no, you'll get jumpscared. It was just done for fun, using simple HTML ...

Creating a specialized child node in RABL for a collection: Tips and tricks

{ sum: 250, page: 3, info: [ { id: 1, name: "Foo", ...}, { id: 2, name: "Bar", ...} ] } I am aiming to establish a format similar to this one. The content of id and name fields are generated randomly and not stored in any vari ...

Loading textures for cubes using Three.js TextureLoader and CubeGeometry

I am currently learning threejs and I am trying to apply 6 different textures to each side of a cube. I initially achieved this using loadTexture. var material3 = new THREE.MeshPhongMaterial( {map: THREE.ImageUtils.loadTexture('textures/ps.png') ...

Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new ro ...

Converting JSON objects to C# Dictionary using WCF DataContract

I am attempting to deserialize a JSON dictionary that I receive from a python application over HTTP into a Dictionary in C#. The structure of the JSON object is as follows: { "native_dict": { "foo": 0, "bar": 1 }, "obj_dict": ...

Retrieve the most recent three time-related json components

My json array contains elements in the following format: { "CKey": "S2_123_45_20130416105655", "TimeOfCall": "2013-04-17T06:00:00-04:00", "DestinationNumber": "123456789", "CallType": "X", "CardNumber": "" } In this array, I am intere ...

Converting a column of JSON strings into a DataFrame

I am faced with a dataframe containing a column called data, structured as follows: data ---- '{"user":"[1,2]", "name":"[John,Doe]"}' '{"user":"[3,4]", "name":"[Foo,B ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

Include a fresh attribute within the existing JSONArray

My situation is as follows: "sections": [ { "id": XXXX, "tipology": "TIPOLOGY" }, { "id": XXXX, "tipology": "TIPOLOGY" }, {"num": 2} ], I am currently utilizing JSONArray and JSONObject. I ...

Store information retrieved from the API into a dataframe

Upon retrieving data from an API, I have the following format of output: {'Textbook': [{'Type': 'Chapters', 'Case': 'Ch09', 'Rates': [{'Date': '2021- 04-23T00:00:00', 'Ra ...

Having trouble resolving bugs in a PHP script designed to update the status of 'open' or 'close' in a database

Seeking some assistance! :) Context of the issue: I manage an SQL database containing unique items with three columns: [index] [id] [status] [index] = incremented number [id] = unique string identifier [status] = '0' for open worksta ...

Instructions on expanding values in multi-dimensional arrays by adding items

I am currently working on a project which involves handling an elaborate list of lists that include names, monetary values, and more. I have encountered challenges when attempting to update the individual sub-lists within the primary list based on user inp ...