-8
votes

Obtenez une chaîne d'objet JavaScript

J'ai un objet JavaScript.

A or B
C or D
E or F
G or H


1 commentaires

Publiez vos devoirs comme un exemple de reproductible minimal


4 Réponses :


2
votes

vous pourriez

  • Obtenez les entrées de l'objet, LI>
  • Paire deux entrées, li>
  • Carte La lettre de la valeur de la raterme, li>
  • Rejoignez le tableau à une seule chaîne. LI> ul>

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


0 commentaires

0
votes
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('');

0 commentaires

0
votes

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


0 commentaires

1
votes

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


0 commentaires