I am looking for a JavaScript function which accepts two string arrays of equal length and outputs a single string array which is the same length as the input arrays, containing the element-wise-concatenated strings of the input arrays. Is there a built-in JavaScript function which does this?
Additionally, I would like to add in a string between the concatenated elements when the element-wise concatenation is done. For example, so that this would be true for each i
:
outputArray[i] = inputArray1[i] + " - " + inputArray2[i]
You could reduce an array with the single arrays. This works for more than one array as well.
var inputArray1 = ['abc', 'def', 'ghi'],
inputArray2 = ['3', '6', '9'],
outputArray = [inputArray1, inputArray2].reduce((a, b) => a.map((v, i) => v + ' - ' + b[i]));
console.log(outputArray);
More functional
var inputArray1 = ['abc', 'def', 'ghi'],
inputArray2 = ['3', '6', '9'],
outputArray = [inputArray1, inputArray2]
.reduce((a, b) => a.map((v, i) => [].concat(v, b[i]))) // get single parts
.map(a => a.join(' - ')); // join inner arrays
console.log(outputArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With