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

250
Views
Función de mapa recursivo para matriz anidada

Estoy tratando de crear una función de mapa que admita la computación de matrices anidadas, usando recursividad:

Esta función, cuando se usa una matriz unidimensional (por ejemplo, [1,2,3,4] ), funciona bien:

 const map = (oldArray, callback, newArray = []) => { //base case: check if there are any items left in the original array to process if (oldArray.length <= 0){ //if all items have been processed return the new array return newArray } else { //destructure the first item from old array and put remaining in a separate array const [item, ...theRest] = oldArray // create an array of the current new array and the result of the current item and the callback function const interimArray = [...newArray, callback(item)] // return a recursive call to to map to process the next item. return map(theRest, callback, interimArray) } }

Pero quiero admitir una matriz anidada, así que, por ejemplo, tengo una matriz como esta:

 const array = [1,[1,2],3]

y quiero aplicar una función, eg: (x)=>x+1;

Tengo esta implementación hasta ahora, pero no puedo entenderla.

 function rnMap(oldArr, fn, newArr = []) { const [item, ...rest] = oldArr; if (oldArr.length <= 0) { return newArr; } else if (Array.isArray(item)) { return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]); } else { const interimArray = [...newArr, fn(item)]; return rnMap(rest, fn, interimArray); } } const rnRes = rnMap(nArr, (e) => { return e + 1; }); console.log(rnRes);

Devuelve [ 2, [ 2, 2 ], 2, 2 ] pero se supone que devuelve [2,[2,3],4]

Si alguien pudiera ayudarme se lo agradecería. Gracias por adelantado.

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

0

Sin enfoque de bucle, una especie de...

 const map = ([value, ...array], fn) => { if (value === undefined) return []; return [ (Array.isArray(value) ? map(value, fn) : fn(value)), ...map(array, fn) ]; }, array = [1, [1, 2], 3], fn = x => x + 1; console.log(map(array, fn));

about 4 years ago · Juan Pablo Isaza Report

0

Esta sería probablemente la solución más simple.

 // @ts-ignore const func = (list: Array<any>) => { return list.map(i => { if (i instanceof Array) { return func(i) } return i+1 }) } const result = func([1,[1,2],3]) console.log('log result', result)

Esto está escrito a typescript , avísame si quieres una versión js

about 4 years ago · Juan Pablo Isaza Report

0

Finalmente encontré el error, aquí está mi solución:

 function rnMap(oldArr, fn, newArr = []) { const [item, ...rest] = oldArr; if (oldArr.length <= 0) { return newArr; } else if (Array.isArray(item)) { return rnMap(rest, fn, [...newArr, rnMap(item, fn, [])]); } else { return rnMap(rest, fn, [...newArr, fn(item)]); } } const rnRes = rnMap([1, 2, [3, 4, [5, 6]], 7], (e) => { return e + 1; }); console.log(rnRes);
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!