簡體   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