繁体   English   中英

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

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

我正在尝试比较Javascript对象中的两个元素。 具有最高价值的字母,应连同其携带的数字一起返回。

这是对象,我们应该返回a和39。

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

到目前为止,这是我的代码。

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})

我认为if语句中的object [i + 1]会将下一个索引元素与当前元素进行比较,但事实并非如此,您将如何实现?

编辑 是否有两个元素具有相同的值,然后返回两个元素

对于像我这样的编码新手来说,这可能是最简单的方法。 此代码返回对象中保存的最高编号。

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})

在每次迭代中,检查当前或先前的键值是否最大,然后进行存储。 存储在最大的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})); 

建议的解决方案:

使用Object.entries()获取键|值对。 使用Array.reduce()迭代,选择具有最高值(索引1)的对。 解构所述减少的结果(与阵列[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)

返回对象键

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

这将是正确的代码:

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})

您可以收集关键点并使用最大值渲染对象。

 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 })); 

当您确实let i in object ,您将遍历对象中的每个 因此,在这种情况下, i将是A,B,c和d,在每次迭代后分别。

这就是object[i+1]不起作用的原因。 因为在第一次迭代中,当i为“ a”时,解释器将其读取为object['a' + 1] ,结果为object['a1']

有几种方法可以解决此问题。

一种方法是使用Object类的keys函数,该函数返回一个键数组,然后您可以在该结果上调用map来遍历每个键,并且每个索引都有一个索引。 即:

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} );

您可以使用的另一种方法是使用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} );

在上述情况下, i将始终是一个数字。 然后,我们遍历对象中存在的键的数量,然后使用i来获取所需的键。 然后将该键放入对象中,我们将获得您要比较的值。

要获取所有索引/值(如果存在多个最大值),

  1. 使用Object.entries获取键/值对,

  2. 然后在使用Array.reduce循环对时,设置reduce = {max:0, data:[]}的初始值

注释: max保存最大值, 数据保存具有最大值的对。 并假设值> 0,因此将初始值设置为max = 0(您可以根据需要更改初始值)。

  1. 在循环中,比较值,

如果cur > max ,将其推入pre.data并更新pre.max。

如果cur===max ,则将其推送到pre.data,

如果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.

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