Write a function that combines two arrays by alternatingly taking elements from each array in turn.
두 개의 배열이 주어지는, 배열은 길이가 달라질 수 있다. 각 배열의 요소를 순서대로 번갈아 넣은 새로운 배열을 반환하는 문제.
투 포인터 알고리즘 문제,
배열의 길이를 판별할 수 있는 변수를 판별할 수 있는 함수를 작성하고, 판별된 길이만큼 for문을 돌며 빈 배열에 요소를 집어 넣는다.
빈 배열에 요소를 담을때는 기준 배열에 요소가 있을때만 들어가도록 if문을 작성한다.
if(a[i]) {
result.push(a[i]);
}
if(b[i]) {
result.push(b[i]);
}
// 배열을 번갈아 넣는 문제
// 투 포인터 알고리즘
function solution(s, n) {
let answer = [];
const sLen = s.length;
const nLen = n.length;
let longer;
if (sLen >= nLen) {
longer = sLen;
} else {
longer = nLen;
}
for (let i = 0; i < longer; i++) {
if (s[i]) {
answer.push(s[i]);
}
if (n[i]) {
answer.push(n[i]);
}
}
return answer;
}
const s = ['a', 'b', 'c', 'd', 'e'];
const n = [1, 2, 3, 4, 5, 6];
console.log(solution(s, n));
function mergeArrays(a, b) {
const result = [];
while (a.length || b.length) {
if (a.length) {
result.push(a.shift()); // 가장 앞에 위치한 배열의 요소를 반환하는 shift()
}
if (b.length) {
result.push(b.shift());
}
}
return result;
}
function mergeArrays(a, b) {
let answer = [];
for (i = 0; i < Math.max(a.length, b.length); i++) { // 배열의 길이를 알아서 판단하도록 Math.max를 이용한 풀이식
if (i < a.length) {
answer.push(a[i]);
}
if (i < b.length) {
answer.push(b[i]);
}
}
return answer;
}
const _ = require('loadash')
function mergeArras(a, b) {
return _.compact(_.flatten(_.zip(a, b)))
}