Iterating through an array of objects and extracting values from unspecified keys

Calculating which color holds a higher value in each array element of the data. Then adding the color with the higher value to an empty object, or increasing the count if already present. Finally, sorting the totals object from highest to lowest based on the total values and returning the color with the highest value.

Facing challenges mapping over this structured array as the property keys are not consistent. Should I consider restructuring it?

*I am open to redesigning the data structure if necessary, so please suggest if there's an easier solution with a different design!

data = [
   { orange: 4, green: 4},
   { green: 0, yellow: 0},
   { yellow: 1, orange: 4 },
   { blue: 2, green: 1 }, 
   { blue: 2, yellow: 1 }, 
   { green: 3, yellow: 2 },
   { green: 1, blue: 3},
   { green: 5, yellow: 2 }, 
 ]

totals = {
  blue: 3,
  green: 2,
  orange: 1,
}

Solution: highValueColor = blue

// PSEUDOCODE //map over the array => data.map() //identify highest value between two elements => propA - propB //check to see if the color's (key) in the element has already been added to totals object //IF the key does not yet exist, create a property in the tally object with the color(key) and set its value to 1 //IF the key is already listed in tally object, increment its property value by 1 => ++ //sort totals object => Math.max() //return highest value color

Answer №1

It's worth noting that there may be a small issue with @hopzebordah's answer, as it seems to count a color even when two colors have the same value. For example, { orange: 4, green: 4} would be counted as orange.

In the comments, I provided an alternative version using map since you appeared to show interest in that method. However, I might have misinterpreted your intended goal.

If you only require the highest value and not necessarily a sorted object, then skipping the sorting step might be more efficient. You can see this in action with highest_value_unsort.

const data = [
  { orange: 4, green: 4},
  { green: 0, yellow: 0},
  { yellow: 1, orange: 4 },
  { blue: 2, green: 1 }, 
  { blue: 2, yellow: 1 }, 
  { green: 3, yellow: 2 },
  { green: 1, blue: 3},
  { green: 5, yellow: 2 }, 
];

const pick_color = (color_obj) => {
  const [[color1, val1], [color2, val2]] = Object.entries(color_obj);
  
  return val1 === val2 ?
    null :
    val1 > val2 ?
        color1 :
        color2;
};


const unsorted = {};
for(const color_obj of data) {
  const color = pick_color(color_obj);
  
  if(color) {
    unsorted[color] = (unsorted[color] ?? 0) + 1;
  }
}

// version of the above using reduce:
// const unsorted = data.reduce((acc, val) => {
//   const color = pick_color(val);
//   
//   return !color ?
//     acc :
//     { ...acc, [color]: (acc[color] ?? 0) + 1 };
// }, {});

// version of the above using map then reduce:
// const unsorted = data
//   .map(pick_color)
//   .reduce(
//     (acc, color) => !color ?
//       acc :
//       { ...acc, [color]: (acc[color] ?? 0) + 1 },
//     {}
//   );

const sorted = Object.fromEntries(
  Object.entries(unsorted)
    .sort(([, a_val], [, b_val]) => b_val - a_val)
);

const highest_value = Object.entries(sorted)[0][0];
const highest_value_unsort = Object.entries(unsorted)
  .reduce(
    (acc, entry) => entry[1] > acc[1] ? entry : acc,
    ['none', 0]
  )[0];

console.log(sorted);
console.log(highest_value);
console.log(highest_value_unsort);

If you're unfamiliar with some of the techniques used above, here are some handy reference links:

Answer №2

If you're using JS, consider yourself lucky!

Setting and getting data in JS objects is a breeze with the { [someVariable]: value } notation. You can also easily check for key existence using the in operator:

const obj = { red: 'foo' };
const red = 'red';
console.log(red in obj) // true
console.log('red' in obj) // true
console.log(blue in obj) // false

With some simple loops, you can get this result:

const data = [
   { orange: 4, green: 4},
   { green: 0, yellow: 0},
   { yellow: 1, orange: 4 },
   { blue: 2, green: 1 }, 
   { blue: 2, yellow: 1 }, 
   { green: 3, yellow: 2 },
   { green: 1, blue: 3},
   { green: 5, yellow: 2 }, 
 ];
 
const totals =  {};

for (const colors of data) {
    const [color1, color2] = Object.keys(colors);
    let color = color1;
    if (colors[color1] < colors[color2]) {
        color = color2
    }
    totals[color] = totals[color] ? totals[color] + 1 : 1;
}

console.log(totals) // { orange: 2, green: 3, blue: 3 }

This solution isn't optimized for performance due to the structure of your data requiring iteration over each value to check keys and values.

JS objects are incredibly versatile and can offer faster solutions depending on dataset size and potential performance constraints.

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

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

Experiencing a service error when trying to load in certain browsers, although it does work properly in Chrome and

I am facing an issue with my service method which is showing errors in multiple browsers including Internet Explorer 8, Chrome, and Firefox 8.0.1. The error message is: OPTIONS http://abc/AddRating 405 (Method Not Allowed) Interestingly, the service met ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

Is there a way to improve scrolling speed on Mobile Safari?

I'm currently working on a project utilizing angularjs and bootstrap, aiming to replicate iOS's navigationController feature. However, I'm encountering speed issues, particularly when scrolling between views on mobile safari iOS. The transi ...

Select the final word and enclose it within a span class

I have a task where I need to identify the last word in a class and then enclose it with a span element so that I can style it using JavaScript. <h1 class="title>A long tile</h1> <h2 class="title>A long tile</h2> should b ...

What could be the reason for the CORS failure when making requests from an HTTPS domain to an HTTP localhost

I have a secure rest service (implemented as an Azure Function), hosted on HTTPS, under domain A. My website is also running securely on HTTPS but on domain B. I've set the CORS to use a wildcard *. Using jQuery on my website, I send Ajax requests ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Generate a Monaco Editor within a Vue.js component

Currently, I am integrating Monaco Editor with Vue.js and facing some confusion regarding how Monaco is being instantiated within the Vue component: 1) In my data() method, I have defined an editorEx object to be used for this purpose, like so: data() { ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

Prevent a <span> element from affecting the linking functionality of an <a> tag

Is it possible to make a hyperlink clickable without including the <span> tags within it and instead attaching a jQuery event to those tags? This is the code I'm using. It utilizes bootstrap's list-group for a navigation element: <ul cl ...

What is the method to obtain the keycode for a key combination in JavaScript?

$(document).on('keydown', function(event) { performAction(event); event.preventDefault(); }); By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combin ...

Retrieve JSON information using PHP and JavaScript SDK exclusivley

After successfully setting up the Facebook Javascript SDK and getting it to display the right information on the page, I have also managed to echo the user into the Firebug console to show the Object containing all of the user profile details. * I am opti ...

Struggling to make cookies stick in IE9

Here is the code snippet I am currently using: <script> var time = new Date(); time.setFullYear(time.getFullYear() + 1, time.getMonth(), time.getDay()); expires = ";expires=" + time.toGMTString(); document.write(expires); doc ...

Tips for correctly updating the status of a checkbox linked to a database

I need some guidance on handling the state change of an input checkbox in React. The checkbox's initial value is determined by a boolean retrieved from a database. Currently, I am using defaultChecked to set the checkbox initially based on this boolea ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

Tips for inserting fresh elements into a numpy array

Initially, I defined an array of size (256, 144, 3). empty_windows = np.empty((256, 144, 3)) My goal was to add new elements to this array using the following method: for i in range(256): for j in range(144): empty_windows[i, j] = np.append(em ...

Troubleshooting: Difficulty Reading .val() on Elements Selected by Class in jQuery.fn.init(9)

I am facing an issue while trying to retrieve all elements with a specific class name using the code below: productPrices = $('.product-price'); Instead of getting individual values, I am getting the following output: jQuery.fn.init(9) [div. ...

Explore the wonders of our solar system using three.js!

I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn. Currently, I have success ...

MySQL's `trader_sma` function retrieves an array suitable for traders

Although I'm not a professional programmer, I do have some knowledge of PHP and can write simple scripts. One script I created downloads prices of all coins from an exchange every minute (using a cron job) to store in my database. Now, I'm lookin ...

Struggling to separate a section of the array

Check out this array: [ '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a171319121b1f163a1f1915080a54191517">[email protected]</a>:qnyynf', '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...