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

205
Views
Oh hombre groupBy() y arrayToObject() me están rompiendo

Así que he estado trabajando en algún crédito extra para mis clases. Soy muy nuevo en la programación y ya busqué ayuda para esta misma tarea, comencé a rodar y ahora estoy absolutamente perdido.

Necesito definir las dos funciones groupBy() y arrayToObect() como se solicita en la siguiente prueba.

No necesariamente estoy buscando la respuesta, pero si alguien pudiera ayudarme a orientarme en la dirección correcta, sería increíble.

Lo que he deducido es lo siguiente:

  1. Necesito estar usando el operador de propagación ...

  2. Necesito crear un newObj = {}

    una. y de alguna manera empujar el elemento derivado de la matriz en el obj

  3. Necesito tomar los valores individuales de la matriz y asignarlos como claves, con las variaciones como propiedades de la clave.

  4. Notación de corchetes

¡Me he estado devanando los sesos durante horas con esto y realmente me vendría bien un poco de orientación!

 describe('groupBy', function () { const input = [4.2, 6.1, 6.3] const result = groupBy(input, (el) => Math.floor(el)) it('returns an object', function () { expect(result).to.be.an('object') }) it('group array items together based on the callback return value', function () { expect(result).to.be.eql({ 4: [4.2], 6: [6.1, 6.3], }) }) }) describe('arrayToObject', function () { const input = ['cat', 'dog', 'bird'] const result = arrayToObject(input, (word) => word + 's') it('returns an object', function () { expect(result).to.be.an('object') }) it('object has original array elements as keys and the result of the callback as values', function () { expect(result).to.be.eql({ cat: 'cats', dog: 'dogs', bird: 'birds', }) }) }) }) groupBy Write a function called groupBy which takes an array and a callback. The function should return an object. Each return value of the callback should be a key of the object and the values should be the input element with which the callback was called. arrayToObject Write a function called arrayToObject which takes an array and a callback. The function should return an object. Each element of the input array should be a key of the returned object and the output from the callback with an element passed in as the corresponding value.
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Estas preguntas han sido respondidas un millón de veces en stackoverflow. Esencialmente, lo que quiere hacer aquí es usar las funciones comunes de matriz js map , filter , reduce , flatten , ..., y piense en cómo su problema puede expresarse en términos de eso.

Una gran cantidad de código del mundo real está transformando datos como este, por lo que es bueno sentirse cómodo haciéndolo.

También tenga en cuenta que la sintaxis extendida copia todo el objeto, lo que puede ser bastante ineficiente. ¡JavaScript no tiene estructuras de datos persistentes! Por lo general, es mejor simplemente mutar, siempre que su código sea el "propietario" del objeto.

 const groupBy = (elts, keyfn) => elts.reduce((m, elt) => { const key = keyfn(elt); m[key] = m[key] || []; m[key].push(elt); return m; }, {});
 const arrayToObject = (elts, fn) => elts.reduce( (obj, elt) => Object.assign(obj, { [elt]: fn(elt) }), {}, );
about 4 years ago · Juan Pablo Isaza Report

0

¡Lo descubrí usando un bucle for!

 function groupBy(arr, callback) { const newObj = {} for (let i = 0; i < arr.length; i++) { if (callback(arr[i])) { const key = callback(arr[i]) newObj[key] = newObj[key] || [] newObj[key].push(arr[i]) } } return newObj }
 function arrayToObject(arr, callback) { const obj = {} for (let i = 0; i < arr.length; i++) { if (callback(arr[i])) { const key = callback(arr[i]) obj[arr[i]] = obj[key] || callback(arr[i]) } } return obj }
about 4 years ago · Juan Pablo Isaza 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!