J'ai un objet JavaScript.
A or B C or D E or F G or H
4 Réponses :
vous pourriez
p>
var object = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 }, result = Object .entries(object) .reduce((r, a, i) => { if (i % 2) { r[r.length - 1].push(a); } else { r.push([a]); } return r; }, []) .map(([a, b]) => a[1] > b[1] ? a[0] : b[0]) .join(''); console.log(result);
var values = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 }; var result = Object.keys(values).reduce(function(result, value, index, array) { if (index % 2 === 0) { result.push(array[values[value] > values[array[index + 1]] ? index : index + 1]) } return result; }, []).join('');
var vs = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 } var letters = []; var numbers = []; var phrase = ""; for (var key in vs) { letters.push(key); numbers.push(vs[key]); } for (var i = 1; i < letters.length; i += 2) { if (numbers[i-1] > numbers[i]) { phrase = phrase + letters[i-1]; } else { phrase = phrase + letters[i]; } }
Je comparais chaque paire dans l'objet puis construisez la chaîne de résultat des plus hautes.
p>
const obj = { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 } //"BCFG" let getHighest = (obj) => { let result = ""; // Convert the object into an array obj = Object.keys(obj).map(function(key) { return [key, obj[key]]; }); // Iterate through the array by i + 2 (skipping 1 in each loop) for (let i = 0, len = obj.length; i < len; i += 2){ // The first one of each pair is more than the other one if (obj[i][1] > obj[i+1][1]){ // Add the letter to the result result += obj[i][0]; } // The second is greater or equal else { // Add the letter to the result result += obj[i+1][0]; } } return result; } console.log(getHighest(obj));
Publiez vos devoirs comme un exemple de reproductible minimal