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

165
Views
¿Hay alguna manera de "girar" de manera eficiente una matriz multidimensional?

Tengo una matriz de matrices formateadas de la siguiente manera:

 [['BTC', '2022-04-27', '39151.53'], ['BTC', '2022-04-26', '37730.20'], ['BTC', '2022-04-25', '39151.53'], ['ETH', '2022-04-27', '39151.53'], ['ETH', '2022-04-26', '37730.20'], ['ETH', '2022-04-25', '39151.53']]

Con lo que me gustaría terminar es:

 [['Date', 'BTC, 'ETH'], ['2022-04-27', '39151.53', '39151.53'], ['2022-04-26', '37730.20', '39151.53'], ['2022-04-25', '39151.53', '39151.53']]

¿Hay alguna forma no complicada de resolverlo?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Podría tomar un objeto con los tipos de las columnas y los índices del objetivo. Luego busque la fila y asigne el tipo a la celda deseada.

 const data = [['BTC', '2022-04-27', '39151.53'], ['BTC', '2022-04-26', '37730.20'], ['BTC', '2022-04-25', '39151.53'], ['ETH', '2022-04-27', '39151.53'], ['ETH', '2022-04-26', '37730.20'], ['ETH', '2022-04-25', '39151.53']], types = { Date: 0, BTC: 1, ETH: 2 }, result = data.reduce((r, [type, date, value]) => { let row = r.find(a => a[types.Date] === date); if (!row) r.push(row = [date, ...Array(Object.keys(types).length - 1).fill('0')]); row[types[type]] = value; return r; }, [Object.keys(types)]); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

Parece que el OP necesita las matrices internas indexadas por el campo de fecha. Esto se puede hacer con reducir. Una vez que haya un índice, recorra las claves (fechas) y recopile los valores asociados con cada fecha.

 const array = [['BTC', '2022-04-27', '39151.53'], ['BTC', '2022-04-26', '37730.20'], ['BTC', '2022-04-25', '39151.53'], ['ETH', '2022-04-27', '39151.53'], ['ETH', '2022-04-26', '37730.20'], ['ETH', '2022-04-25', '39151.53']]; const dateIndex = array.reduce((acc, a) => { let date = a[1]; if (!acc[date]) acc[date] = []; acc[date].push(a); return acc; }, {}); let result = [['Date', 'BTC', 'ETH']]; Object.keys(dateIndex).map(date => { let values = dateIndex[date].map(arr => arr[2]); result.push([date, ...values]); }); console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

Aquí otra solución usando reduce() .

Esto primero crea un objeto JavaScript que permitiría búsquedas rápidas de un valor específico para una moneda y fecha dadas dentro de un programa y luego transforma ese objeto para crear el resultado solicitado por OP. También arrojará un error por datos de entrada incorrectos cuando, por ejemplo, habría dos valores para una moneda y una fecha dadas.

 const input = [ ["BTC", "2022-04-27", "39151.53"], ["BTC", "2022-04-26", "37730.20"], ["BTC", "2022-04-25", "39151.53"], ["ETH", "2022-04-27", "39151.53"], ["ETH", "2022-04-26", "37730.20"], ["ETH", "2022-04-25", "39151.53"], ]; function pivot(input){ return input.reduce((perDay, [currency, date, value]) => { if(perDay[date]) { // we already have a value for this day if(perDay[date][currency]){ // we already have a value for this currency and day => error throw new Error(`Two values for for the same day. Currency: ${currency}, Day: ${date}`); } // add value for another currency for that day else perDay[date][currency] = value; } else perDay[date] = { [currency]: value }; return perDay; }, {}) } // result as a JS object which will allow quick lookups const pivotted = pivot(input); console.log("Result as JavaScript object") console.log(pivotted); // result transformed to your expected result const result = Object.entries(pivotted).map(([date, values]) => [date, ...Object.values(values)]); result.unshift(['Date', 'BTC', 'ETH']); console.log("Result as JavaScript nested array") console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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!