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

212
Views
¿Cómo hacer un bucle y empujar el acumulador de una función de reducción?

Estoy tratando de reducir una matriz y transformarla en una matriz múltiple.

 const array = [ { a: 1, b: 6 }, { a: 1, b: 5 }, { a: 1, b: 6 }, { a: 1, b: 4 }, { a: 1, b: 5 } ]; var newArray = array.reduce( (memo, curr) => { memo.forEach((item, key) => { const found = item.filter((el) => el.a === curr.a && el.b === curr.b); if (found.length > 0) return memo[key].push(curr); else return memo.push([curr]); }); return memo; }, [[]] );

El resultado necesario que trato de obtener es

 [ [ { a: 1, b: 5 }, { a: 1, b: 5 } ], [ { a: 1, b: 6 }, { a: 1, b: 6 }, ], [ { a: 1, b: 4 }, ] ];

Pero como puede ver si lo intenta, porque presiono el memorándum, el bucle continúa disparando. Y el resultado contiene cientos de matrices.

¿Cómo se supone que debo hacer para limitar este ciclo y obtener el resultado correcto?

Muchas gracias por adelantado :)

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

0

Puede usar Map para agrupar el elemento por la clave de {a, b} y luego obtener los valores del grupo

 const array = [ { a: 1, b: 6 }, { a: 1, b: 5 }, { a: 1, b: 6 }, { a: 1, b: 4 }, { a: 1, b: 5 }, ]; var newArray = Array.from( array .reduce((map, curr) => { const key = JSON.stringify({ a: curr.a, b: curr.b }); if (!map.has(key)) { map.set(key, []); } map.get(key).push(curr); return map; }, new Map()) .values() ); console.log(newArray);

about 4 years ago · Juan Pablo Isaza Report

0

Mira tu código. Tiene un bucle anidado triple, que es una locura y definitivamente no es necesario para lograr esto. ¿Por qué no usar un mapa?

Aquí hay una función que hará lo que quieras hacer con cualquier arreglo de objetos dado.

 const array = [ { a: 1, b: 6 }, { a: 1, b: 5 }, { a: 1, b: 6 }, { a: 1, b: 4 }, { a: 1, b: 5 }, ]; const separate = (arr) => { const reduced = arr.reduce((acc, curr) => { const path = JSON.stringify(curr); if (!acc[path]) acc[path] = []; acc[path].push(curr); return acc; }, {}); return Object.values(reduced); }; console.log(separate(array));

about 4 years ago · Juan Pablo Isaza Report

0

Si presiona dentro del bucle, también lo hará para cada iteración de la función de reducción.

puede lograr agregando algunas variables locales como aquí

 const array = [ { a: 1, b: 6 }, { a: 1, b: 5 }, { a: 1, b: 6 }, { a: 1, b: 4 }, { a: 1, b: 5 } ]; // shift changes the orginal array // it will remove and return firstElement var firstElement = array.shift(1); var newArray = array.reduce( (memo, curr) => { let isFound = false; let index = 0; memo.forEach((item, key) => { const found = item.filter((el) => el.a === curr.a && el.b === curr.b); if(found.length > 0){ index = key; isFound = true; return; } }); if(isFound) { memo[index].push(curr); } else { memo.push([curr]); } return memo; }, [[firstElement]] ); console.log(newArray);

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!