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

226
Views
La mejor manera de crear una matriz a partir de un objeto que tiene varias copias

De un objeto como este:

 {a:1, b: 2, c: 3}

me gustaría convertirme

 ['a', 'b', 'b', 'c', 'c', 'c']

Donde la clave es la cadena y el valor es el número de copias, el orden no importa.

¿Cuál es la mejor manera de hacer esto?

Estaba pensando en usar array.fill, pero no estoy seguro de si eso es realmente más fácil que simplemente iterar y empujar.

Editar: Actualmente esto:

 const arr = [] _.each(obj, function (v, k) { _.times(v, function () { arr.push(k) }) })
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Puede hacer un flatMap las entradas de Object.entries y fill una matriz de cada tamaño.

 const obj = { a: 1, b: 2, c: 3 }; const result = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k)); console.log(result)

o con Lodash

 const obj = { a: 1, b: 2, c: 3 }; const arr = _.flatMap(obj, (v,k) => Array(v).fill(k)) console.log(arr);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

Pero no hay nada como un bucle simple

 const obj = { a: 1, b: 2, c: 3 }; const result = [] for (let [k, v] of Object.entries(obj)) { while (v--) { result.push(k) } } console.log(result)

about 4 years ago · Santiago Gelvez Report

0

Puede usar Object.entries y Array#reduce de la siguiente manera:

 const input = {a:1, b: 2, c: 3}; const output = Object.entries(input).reduce( (prev, [key,value]) => prev.concat( Array(value).fill(key) ), [] ); console.log( output );

O, usando Array#push en lugar de Array#concat ,

 const input = {a:1, b: 2, c: 3}; const output = Object.entries(input).reduce( (prev, [key,value]) => prev.push( ...Array(value).fill(key) ) && prev, [] ); console.log( output );

O, usando bucles for ,

 const input = {a:1, b: 2, c: 3}; const output = [], pairs = Object.entries(input); for(let i = 0; i < pairs.length; i++) { const [key, value] = pairs[i]; for(let j = 0; j < value; j++) { output.push( key ); } } console.log( output );

about 4 years ago · Santiago Gelvez Report

0

Convertiría el objeto en una matriz de claves usando Object.keys y luego usaría una matriz de resultados vacía recién creada, luego mapearía a través de las claves.

Para cada clave, agregaría una matriz de relleno a los resultados existentes.

Aquí está la solución ES6 para eso (no se requieren bibliotecas adicionales)

 const obj = { a: 1, b: 2, c: 3 }; let result = [] Object.keys(obj).forEach(key => { result = [...result, ...new Array(obj[key]).fill(key)] }) console.log(result)

about 4 years ago · Santiago Gelvez 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!