JavaScript/Node.js中按指定规则合并数组的内置方法探究
Hey there! Great question. Unfortunately, JavaScript doesn't have a built-in method that directly handles this specific custom array merging/string concatenation logic out of the box. But don't worry—we can easily build this using existing array methods to match your desired result.
Let's Break Down Your Pattern
From your example, the logic we need to implement is:
- Pair elements from both arrays at the same index, concatenating them into a single string
- If one array runs out of elements before the other, we take the remaining elements from the longer array as-is (since concatenating with an empty string leaves them unchanged)
Implementation Code
Here's a clean, readable way to achieve this using Array.from to iterate up to the length of the longer array:
const Array1 = ['1', '234', '56']; const Array2 = ['1', '2', '45', '56']; const mergedArray = Array.from( { length: Math.max(Array1.length, Array2.length) }, (_, index) => { // Fallback to empty string if the index doesn't exist in one of the arrays const elem1 = Array1[index] || ''; const elem2 = Array2[index] || ''; return elem1 + elem2; } ); console.log(mergedArray); // Output: ['11', '2342', '5645', '56']
If you prefer a slightly shorter syntax, you can use Array.fill() combined with map() instead:
const maxLength = Math.max(Array1.length, Array2.length); const mergedArray = Array(maxLength).fill().map((_, index) => (Array1[index] || '') + (Array2[index] || '') );
Why No Built-In Method?
JavaScript's core array methods handle general-purpose operations like:
- Merging arrays into one with
concat() - Joining all array elements into a single string with
join() - Transforming elements with
map()
But this specific paired concatenation logic is a niche use case, so there's no dedicated built-in method for it. The good news is that combining existing methods makes it trivial to implement!
内容的提问来源于stack exchange,提问作者LeftN

