Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Cuente las ganancias, los juegos y el tipo de juego en una variedad de objetos y cree objetos de objetos

Estoy seguro de que ya hay una respuesta y una solución "fácil" para esto, pero no encontré nada en la última hora.

Así que tengo este objeto:

 [ { "win": false, "switched": false }, { "win": false, "switched": false }, { "win": true, "switched": true }, { "win": true, "switched": true } ]

que muestra los resultados de cuatro juegos de monty-hall. Quiero crear un objeto de esta matriz que tenga la siguiente estructura:

 { switched: { played: 2, won: 2 }, put: { played: 2, lost: 2 } }

Entonces, en realidad, si el objeto en la matriz superior ha switched: true , quiero aumentar el valor de switched["played"] en 1 y también ha won: true , quiero aumentar el valor de las teclas switched["won"] también por uno. Viceversa para switched: false I wand para poner todo en el objeto de resultados bajo la clave put .

Probé algunos enfoques bastante vergonzosos con reduce , pero creo que debe haber una forma "más fácil" (la mía no funcionó en absoluto...)

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

 const items = [{ win: false, switched: false }, { win: false, switched: false }, { win: true, switched: true }, { win: true, switched: true } ]; const res = items.reduce( (acc, cur) => { // If your current item is switched return cur["switched"] ? { // ... deal with the switched part, leave the rest as is ...acc, switched: { played: acc.switched.played + 1, // increase the played counter by 1, based on whatever your accumulator currently has won: acc.switched.won + Number(cur.win) // cast your win property to number (true -> 1, false -> 0) and increase accordngily } } : { // ... otherwise deal with the put part, leave the rest as is ...acc, put: { played: acc.put.played + 1, lost: acc.put.lost + Number(!cur.win) // negate your win so that it reflects a loss, cast to number and increase accordingly } }; }, // Initialize your accumulator { switched: { played: 0, won: 0 }, put: { played: 0, lost: 0 } } ); console.log(res);

about 4 years ago · Santiago Trujillo Report

0

Creo que podría ayudarte

 const data = [{"win": false,"switched": false},{"win": false,"switched": false},{"win": true,"switched": true},{"win": true,"switched": true}]; const initScores = { switched: { played: 0, won: 0, }, put: { played: 0, lost: 0, } }; const result = data.reduce((acc, {win, switched})=> { if (switched) { acc.switched.played += 1; acc.switched.won += win ? 1 : 0; } else { acc.put.played += 1; acc.put.lost += !win ? 1 : 0; } return acc; }, initScores); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0 }

about 4 years ago · Santiago Trujillo Report

0

Con Array.prototype.reduce , puede proporcionar la lógica en función de la acumulación de objetos acc y la corriente del juego curr .

En el caso de que curr haya sido cambiado, debe asignar la propiedad switched a acc . Sin embargo, puede no estar undefined , por lo que debe asignarlo a un objeto predeterminado si esto sucede.

El mismo inicio de sesión se aplica a la otra parte del problema. Con respecto a la propiedad de put , simplemente reemplace todas aquellas switched por put y won por lost .

 const obj=[{win:false,switched:false},{win:false,switched:false},{win:true,switched:true},{win:true,switched:true}] const output = obj.reduce((acc, curr) => curr.switched ? (acc.switched = ( { won: curr.win ? acc.switched.won + 1 : acc.switched.won, played: acc.switched.played + 1 } ), acc) : (acc.put = ( { lost: !curr.win ? acc.put.lost + 1 : acc.put.lost, played: acc.put.played + 1 } ), acc), { switched: { won: 0, played: 0 }, put: { lost: 0, played: 0 } }) console.log(output)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!