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

323
Views
¿Cómo iterar a través del mapa y presionar teclas con valores similares en la misma matriz?

Tengo un mapa de javascript con una estructura como esta:

 let map = {3 => 1, 15 => 2, 0 => 2, 8 => 3, 9 => 3}

Necesito recibir las matrices de claves, y las claves con valores similares deben estar en la misma matriz.

 [[3], [15,0],[8,9]]

Esto es lo que he intentado:

 let answers = []; let currentVal = 1; map.forEach((value, key)=>{ let subArr = []; if(value === currentVal){ subArr.push(key); answers.push(subArr); currentVal++; } }); return answers;

Y devuelve [[3], [15], [8]]

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

0

Supongo que su mapa es un objeto, no un mapa por razones de legibilidad, pero si está usando Mapa allí, puede cambiar los métodos para obtener elementos, pero la idea principal se puede ver a continuación:

 const data = { 3: 1, 15: 2, 0: 2, 8: 3, 9: 3 }; const customData = Object.entries(data).reduce((acc, [key, value]) => { if (value in acc) { acc[value].push(key); } else { acc[value] = [key]; } return acc; }, {}); const finalArray = Object.values(customData); console.log(finalArray);

Ejemplo de edición con Map() :

 const data = new Map([ [3, 1], [15, 2], [0, 2], [8, 3], [9, 3] ]); const customData = Array.from(data).reduce((acc, [key, value]) => { if (value in acc) { acc[value].push(key); } else { acc[value] = [key]; } return acc; }, {}); const finalArray = Object.values(customData); console.log(finalArray);
about 4 years ago · Juan Pablo Isaza Report

0

Puede usar Object.entries y clave de desestructuración key, value pero cambio su lugar como value, key para que coincida con el mapa de estructura de datos proporcionado por OP:

 let map = { 3: 1, 15: 2, 0: 2, 8: 3, 9: 3 }; const arr = []; for (const [value, key] of Object.entries(map)) { if (arr[key]) { arr[key].push(value); } else { arr[key] = [value]; } } console.log(arr.filter(Boolean)); // [[3], [15,0],[8,9]]

NOTA arr.filter(Boolean) para eliminar valores falsos (vacíos) de la matriz ya que el índice 0 no tiene una matriz dentro.

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!