简体   繁体   English

如何比较对象中的元素并返回较高的值? * JavaScript *

[英]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. 我正在尝试比较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. 这是对象,我们应该返回a和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? 我认为if语句中的object [i + 1]会将下一个索引元素与当前元素进行比较,但事实并非如此,您将如何实现?

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. 存储在最大的largest变量。 In the end return the largest variable, and it's value ( object[largest] ): 最后,返回largest变量及其值( 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. 使用Object.entries()获取键|值对。 Iterate with Array.reduce() , choose the pair with the highest value (index 1). 使用Array.reduce()迭代,选择具有最高值(索引1)的对。 Destructure the reduce's result (an array with [key, value] ) into key and value consts, and use them to build the return object. 解构所述减少的结果(与阵列[key, value] )转换成key和值consts,并使用它们来构建返回的对象。

 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 所以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. 当您确实let i in object ,您将遍历对象中的每个 So in this case, i would be a, b, c, and d, respectively after each iteration. 因此,在这种情况下, i将是A,B,c和d,在每次迭代后分别。

That's why object[i+1] doesn't work. 这就是object[i+1]不起作用的原因。 Because on the first iteration when i is "a", the interpretter reads it as object['a' + 1] which results to object['a1'] . 因为在第一次迭代中,当i为“ a”时,解释器将其读取为object['a' + 1] ,结果为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. 一种方法是使用Object类的keys函数,该函数返回一个键数组,然后您可以在该结果上调用map来遍历每个键,并且每个索引都有一个索引。 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: 您可以使用的另一种方法是使用for循环并创建迭代器变量,如下所示:

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. 在上述情况下, i将始终是一个数字。 Then we loop through the number of keys there are in the object, and then use i to get the key we want. 然后,我们遍历对象中存在的键的数量,然后使用i来获取所需的键。 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, 使用Object.entries获取键/值对,

  2. then when using Array.reduce to loop the pairs, set the initial value of reduce = {max:0, data:[]} 然后在使用Array.reduce循环对时,设置reduce = {max:0, data:[]}的初始值

Comment: max saves the max value, data saves the pairs with max value. 注释: max保存最大值, 数据保存具有最大值的对。 And assuming the values is > 0, so set the initial value of max = 0 (you can change the initial value as you need). 并假设值> 0,因此将初始值设置为max = 0(您可以根据需要更改初始值)。

  1. In the loop, compare the value, 在循环中,比较值,

if cur > max , push it into pre.data and update pre.max. 如果cur > max ,将其推入pre.data并更新pre.max。

if cur===max , push it to pre.data, 如果cur===max ,则将其推送到pre.data,

if cur<max , do nothing. 如果cur<max ,则什么也不做。

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在javascript object中比较得到object的值 - How to compare and get object value in javascript object 如何将 object 与数组进行比较并返回值 - How to compare an object with an array and return a value 如何将 arrays 与高阶函数进行比较? JavaScript - How to compare arrays with higher order functions? JavaScript JavaScript比较对象中的值 - Javascript compare value in object 使用高阶函数,如果另一个值为true,则返回一个对象值(JavaScript) - Using a higher order function, return one object value if another value is true (JavaScript) 如何比较 Javascript 中的 2 arrays 中的对象并返回缺失的元素? - How can I compare objects in 2 arrays in Javascript & return the missing elements? Javascript标准对象-如何返回两个元素? - Javascript Standard Object - How To Return Two Elements? 如何在javascript中遍历和比较数组元素内的对象 - how to traverse and compare object inside an array elements in javascript 如何比较 object 的 2 个数组并返回 Javascript 中的单个数组结果? - How to compare 2 array of object and return single array outcome in Javascript? 如何在javascript中比较和更改对象值数组与对象键 - How to compare and change array of object value with object key in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM