简体   繁体   中英

How to compare elements in an object and return the higher value? *Javascript*

I am trying to compare two elements inside an object in Javascript. The letter that has the highest value, should be returned along with the number it carries.

This is the object and we should return a and 39.

obj({a:39,b:21,c:12,d:4}) // should return a : 39

Here is my code so far.

let obj = object => {

  for(let i in object) { // i  represents the "key" of the objects, a,b,c,d
    if(object[i] > object[i + 1]) { // object[i] represents the "value" held 39,21,12,4
      console.log(i + ":" + object[i]);
    } else {
      console.log(i + ":" + object[i]);
    }
  }
}

obj({a:39,b:21,c:12,d:4})

I thought object[i + 1] in the if statement would compare the next indexed element to the current one but it doesn't, how would you accomplish this?

EDIT if there are two elements with the same value then return both of the elements

This is probably the easiest way to accomplish this for people new to coding like me. This code returns the highest number held in the object.

let getMax = (obj) => {
  let highestValue = 0;
  for(var i in obj) {
    if(highestValue < obj[i]) {
      highestValue = obj[i];
    } else if (highestValue == obj[i]) {
      highestValue = highestValue + " " + obj[i];
    }
  }
  alert(highestValue);
}
getMax({John:300000,Kary:360000,David:2700000,Michelle:2700000})

On each iteration check if the current or previous key value is the largest, and store. Store the largest in the largest variable. In the end return the largest variable, and it's value ( object[largest] ):

 let obj = object => { let largest; for(const i in object) { // i represents the "key" of the objects, a,b,c,d if(!largest || object[i] > object[largest]) { largest = i; } } return { [largest]: object[largest] }; } console.log(obj({a:39,b:21,c:12,d:4})); 

Suggested solution:

Use Object.entries() to get key|value pairs. Iterate with Array.reduce() , choose the pair with the highest value (index 1). Destructure the reduce's result (an array with [key, value] ) into key and value consts, and use them to build the return object.

 const obj = (object) => { const [key, value] = Object.entries(object) .reduce((r, e) => e[1] > r[1] ? e : r); return { [key]: value }; }; console.log(obj({a:39,b:21,c:12,d:4})); 

for(let i in object)

returns object keys

so i+1 = a : a1, b:b1, c:c1

This will be the correct code:

let obj = object => {
let returnValue;
for(let i in object) { // i  represents the "key" of the objects, a,b,c,d
  if(typeof(returnValue)==="undefined"){
    returnValue = object[i];
  } else if (object[i] > returnValue) {
    returnValue=object[i];
  }
}
return returnValue;
}
obj({a:39,b:21,c:12,d:4})

You could collect the keys and the render the object with the max values.

 function getMax(object) { return Object.assign( ...Object .keys(object).reduce((r, k) => { if (!r || object[r[0]] < object[k]) { return [k]; } if (object[r[0]] === object[k]) { r.push(k); } return r; }, undefined) .map(k => ({ [k]: object[k] })) ); } console.log(getMax({ a: 39, b: 21, c: 12, d: 4, foo: 39 })); 

When you do let i in object , you're iterating through every key in the object. So in this case, i would be a, b, c, and d, respectively after each iteration.

That's why object[i+1] doesn't work. Because on the first iteration when i is "a", the interpretter reads it as object['a' + 1] which results to object['a1'] .

There's a few ways you can approach this.

One method would be to use the Object class's keys function, which returns an array of keys and then you can call map on that result to loop through each key and you'll also have a index to each one. Ie:

let obj = object => {
  var keys = Object.keys(object);
  keys.map(function(key, index) {
    console.log("Current value: " + object[key]);
    console.log("Current index: " + index);
    console.log("Current key: " + key);
    console.log("Next value: " + object[keys[index + 1]]); // you should probably check if you're at the last index before you do this
    console.log("-------------");
  });
};
obj( {a:39,b:21,c:12,d:4} );

Another route you can go is using a for loop and creating an iterator variable, like so:

let obj = object => {
  var keys = Object.keys(object);

  for(var i = 0; i < keys.length; i++) {
    console.log('Current Value: ' + object[keys[i]]);
    console.log('Next Value: ' + object[keys[i + 1]]); // also probably do a check here to see if you're already at the last index
  }
};
obj( {a:39,b:21,c:12,d:4} );

In the case above, i would always be a number. Then we loop through the number of keys there are in the object, and then use i to get the key we want. Then put that key into the object and we'll get the values you want to compare by.

To get all index/value (if exists multiple max values),

  1. use Object.entries to get key/value pairs,

  2. then when using Array.reduce to loop the pairs, set the initial value of reduce = {max:0, data:[]}

Comment: max saves the max value, data saves the pairs with max value. And assuming the values is > 0, so set the initial value of max = 0 (you can change the initial value as you need).

  1. In the loop, compare the value,

if cur > max , push it into pre.data and update pre.max.

if cur===max , push it to pre.data,

if cur<max , do nothing.

 const obj = {a:39,b:21,c:12,d:4,e:39} result = Object.entries(obj).reduce(function(pre, cur){ if(pre.max < cur[1]){ pre.data = [] pre.max = cur[1] pre.data.push({[cur[0]]:cur[1]}) } else if(pre.max === cur[1]){ pre.data.push({[cur[0]]:cur[1]}) } return pre },{max:0, data:[]}) console.log(result.data) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM