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

211
Views
Cómo crear claves para mis datos de console.log y agregarlos a html (resultado de registro de consola en cuadros de texto)

Estoy haciendo que el sistema de emparejamiento (Jugador contra jugador) sea mi objetivo. ¿Cómo puedo asegurarme de que las claves se agreguen a mi div?

Ya he creado una clave con append antes. Aquí está el fragmento

 const source = [{ entryID: 1, entryName: 'player1', weight: 1900, }, { entryID: 2, entryName: 'player2', weight: 1900, }, { entryID: 3, entryName: 'player3', weight: 1910, }, { entryID: 4, entryName: 'player4', weight: 1910, }, { entryID: 5, entryName: 'player5', weight: 1915, }, { entryID: 6, entryName: 'player6', weight: 1915, }, { entryID: 7, entryName: 'player7', weight: 1920, }, { entryID: 8, entryName: 'player8', weight: 1920, }, { entryID: 9, entryName: 'player9', weight: 1930, }, { entryID: 10, entryName: 'player10', weight: 1930, }, ] const combine = (source) => { return source.reduce((acc, curr) => { if (acc[curr.weight]) { const levelArr = acc[curr.weight]; const last = levelArr[levelArr.length - 1]; if (last.length === 2) { levelArr.push([curr]) } else { last.push(curr) } } else { acc[curr.weight] = [ [curr] ]; } return acc; }, {}) }; var result = combine(source) var html = "" var keys = Object.keys(result) //if there are more than one keys ie : 2.. for (var i = 0; i < keys.length; i++) { result[keys[i]].forEach(function(val) { val.forEach(function(value, index) { var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]" var handlers = index == 0 ? "handlerM[]" : "handlerW[]" var weights = index == 0 ? "weightM[]" : "weightW[]" html += `<input type="text" name="${entryIDs}" value="${value.entryID}"> <input type="text" name="${handlers}" value="${value.entryName}"> <input type="text" name="${weights}" value="${value.weight}"> ` }) }) } document.getElementById("result").innerHTML = html //add html to div console.log(result);
 <div id="result"> </div>

Estos son mis datos después de hacer la función newCombine... Ahora mi objetivo es ¿cómo puedo crear claves y agregar estos resultados como cuadro de texto?

ingrese la descripción de la imagen aquí

El fragmento que proporcioné funciona cuando 2 datos tienen el mismo peso. Se combinan en 1 matriz. Yendo a mi objetivo, ahora, estoy teniendo dificultades para aplicar eso en mi función actual que funciona cuando 2 datos con una diferencia de peso menor o mayor que igual a 15. Por favor, ayúdame. Muchas gracias.

html

 <div id="appendhere"> </div>

ajax

 function newCombine(data, difference) { let nonMatched = [...data] const groups = {} for (let i = 0; i < nonMatched.length - 1; i++) { const first = nonMatched[i] inner: for (let j = nonMatched.length - 1; j > i; j--) { const second = nonMatched[j] const delta = Math.abs(first.weight - second.weight) if (delta <= difference && first.entryName !== second.entryName) { const groupKey = `${first.weight}_${second.weight}` groups[groupKey] = [first, second] nonMatched = nonMatched.filter( obj => obj.entryID != first.entryID && obj.entryID != second.entryID ) i = -1 break inner } } } return { ...groups, ...nonMatched } } $(document).ready(function() { var entry_list =$('#entry_list1').DataTable({ "ajax": { "url": "<?php echo site_url('report/controlget')?>", "type": "get", success: function(data) { const source = data; const a = newCombine(source, 15); console.log(a); //How can i append my key here? }, } }); });
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Introducción

Evitaré las cosas relacionadas con la consola y div aquí para asegurarme de que la solución sea reutilizable de cualquier manera. Puede hacer con el resultado lo que quiera, incluso agregarlo a un div o mostrarlo en la consola.

Planteamiento del problema

Necesitamos agrupar elementos usando los criterios, según los cuales la diferencia de peso es menor que un valor dado, p. 15.

La perfección es inalcanzable

Consideremos el ejemplo cuando tenemos pesos como 1900, 1910 y 1920. No podemos tener un grupo de peso de (1900, 1910 y 1920) porque 1920 - 1900 = 20 > 15.

Podríamos tener grupos de peso como (1900, 1910), (1920) o (1900), (1910, 1920)

Una solución imperfecta, pero probablemente lo suficientemente buena

 const source = [{ entryID: 1, entryName: 'player1', weight: 1900, }, { entryID: 2, entryName: 'player2', weight: 1900, }, { entryID: 3, entryName: 'player3', weight: 1910, }, { entryID: 4, entryName: 'player4', weight: 1910, }, { entryID: 5, entryName: 'player5', weight: 1915, }, { entryID: 6, entryName: 'player6', weight: 1915, }, { entryID: 7, entryName: 'player7', weight: 1920, }, { entryID: 8, entryName: 'player8', weight: 1920, }, { entryID: 9, entryName: 'player9', weight: 1930, }, { entryID: 10, entryName: 'player10', weight: 1930, }, ]; let groups = []; for (let item of source) { let found = false; for (let group of groups) { if (!found) { let isFit = true; for (let element of group) { if (Math.abs(element.weight - item.weight) > 15) isFit = false; } if (isFit) { group.push(item); found = true; } } } if (!found) groups.push([item]); } document.getElementById("foo").innerText = JSON.stringify(groups);
 <div id="foo"></div>

Recorremos los elementos e iteramos cada uno en el primer grupo que coincidiría. Si ninguno de los grupos coincide, creamos un nuevo grupo.

over 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!