-2

Hi I am having trouble looping through an array of objects to find the highest property value and return the object that contains that highest property value. Suppose that I have this array of objects:

var eachMapping = [ { I: 1 },
                        { w: 1, a: 1, n: 1, t: 1 },
                        { t: 1, h: 1, i: 1, s: 1 },
                        { w: 1, o: 1, r: 1, d: 6 } ];


    var largest = 0;
        for(var i = 0; i < eachMapping.length; i++){
            for(prop in eachMapping){
                if(eachMapping[i][prop] > largest){
                    largest = eachMapping[i][prop]
                    wantedobject = eachMapping[i];
                }
            }
    }

    console.log(wantedobject)

This returns undefined. What I am hoping for is for this loop to return { w: 1, o: 1, r: 1, d: 6 } by assigning this to wantedobject because of all the objects in the array it has a property value that is the highest amongst all the property values in the other objects. Thanks!

theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72

2 Answers2

1

Some basic coding errors - which probably explains the downvotes:

  • not initialising wantedobject
  • not declaring loop variable prop
  • inconsistent use of semicolons
  • biggest error was not using for(var prop in eachMapping[i])

this works:

var eachMapping = [ { I: 1 },
                    { w: 1, a: 1, n: 1, t: 1 },
                    { t: 1, h: 1, i: 1, s: 1 },
                    { w: 1, o: 1, r: 1, d: 6 } ];

var wantedobject = null;
var largest = 0;
    for(var i = 0; i < eachMapping.length; i++){
        for(var prop in eachMapping[i]){
            if(eachMapping[i][prop] > largest){
                largest = eachMapping[i][prop];
                wantedobject = eachMapping[i];
            }
        }
}

console.log(wantedobject);
0
var eachMapping = [ { I: 1 },
                    { w: 1, a: 1, n: 1, t: 1 },
                    { t: 1, h: 1, i: 1, s: 1 },
                    { w: 1, o: 1, r: 1, d: 6 } ];


var largest = 0, i = 0, prop, wantedobject;
for(; i < eachMapping.length; i++){
    for(prop in eachMapping[i]) {//you've missed [i], like Emil G wrote in his comment
        if(eachMapping[i][prop] > largest){
            largest = eachMapping[i][prop]
            wantedobject = eachMapping[i];
        }
    }
}

console.log(wantedobject)
Dmitry
  • 6,716
  • 14
  • 37
  • 39