anoop chandran anoop chandran - 4 months ago 16
Javascript Question

Find parent object with max value

I'm new to javascript, so this question may sound very basic.

var data = [
{ Amy: {items:[{shirt: 12},{trouser: 10}] } },
{ Bill: {items:[{shirt: 10},{trouser: 11}] } },
{ Chet: {items:[{shirt: 11},{trouser: 12}] } }

I am trying to write a function to return who's got max number of shirts. So I write two functions like this to first get the max values

var shirtValues = {return obj.items[shirts]; });
var maxValue = Math.max.apply(null, shirtValues);

Now i need to find who is the person that got max number of shirts. How to achieve that?


I would start by changing your data structure. It's hard to see how the current format would be overly useful for iterating, aggregating, getting the user's name, getting the item's names, etc., without excessive iterating.

Here is one alternative data structure that is much easier to work with because it doesn't have nested arrays and doesn't require Object.keys to access data you need consistently (e.g. user name):

var data = [{
  user: 'Amy',
  items: {
    shirt: 12,
    trouser: 10
}, {
  user: 'Bill',
  items: {
    shirt: 10,
    trouser: 11
}, {
  user: 'Chet',
  items: {
    shirt: 11,
    trouser: 12

With this format, you could easily sort by a particular item quantity:

let getTopItem = (data, itemName) => {
  // 1. clone the array using concat
  // 2. sort by value at supplied itemName
  // 3. return the first item
  let sorted = data.concat().sort((a, b) => {
    return b.items[itemName] - a.items[itemName];
  return sorted.shift();

let topShirts = getTopItem(data, 'shirt');

EDIT - I don't mean this negatively toward any of the answers as they all seem to be correct and useful approaches to getting the required data from the presented data structure - but look at how many iterations they all require to get this very basic data out of your object. Choosing the right structure for your data will save you a lot of headaches down the road.