Me gustaría saber cómo puedo fusionar matrices de esta manera, por ejemplo:
const names = ['MARCUS', 'LUCAS', 'ANDREA'] const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS'] [...merge stuff] // and then the output should be const full_names = ['MARCUS SMITH', 'LUCAS JOHNSON', 'ANDREA WILLIAMS']Aquí, una función zip crea una matriz como [["MARCUS","SMITH"],["LUCAS","JOHNSON"],["ANDREA","WILLIAMS"]] y luego map convierte las matrices internas en cadenas.
const names = ['MARCUS', 'LUCAS', 'ANDREA']; const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS']; const zip = (...arrays) => { let res = []; for(let i = 0; i < arrays[0].length; i++) { res.push([]); for(let j = 0; j < arrays.length; j++) { res[i].push(arrays[j][i]); } } return res; }; const res = zip(names, surnames) .map(([name, surname]) => name + ' ' + surname); console.log(res);Estas son un par de maneras de hacerlo. Se supone que hay una coincidencia 1:1 de nombre y apellido en las dos matrices de entrada.
const names = ['MARCUS', 'LUCAS', 'ANDREA'] const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS'] // way 1: traditional loop const res = []; for (let i = 0; i < names.length; i++) { res.push(`${names[i]} ${surnames[i]}`); }; console.log('full_names: ', res); // way 2: another way - more functional flavor const res2 = names.reduce((acc, e, i) => { acc.push(`${e} ${surnames[i]}`); return acc; }, []) console.log('full_names: ', res2);producción:
[ 'MARCUS SMITH', 'LUCAS JOHNSON', 'ANDREA WILLIAMS' ]Puedes usar la recursividad de la siguiente manera:
const names = ['MARCUS', 'LUCAS', 'ANDREA'], surnames = ['SMITH', 'JOHNSON', 'WILLIAMS'], fn = (n,sn,i,f) => i <= n.length - 1 ? fn(n,sn,i+1,[...f,`${n[i]} ${sn[i]}`]) : f; console.log( fn(names,surnames,0,[]) );