Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise concatenation of string arrays

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]
like image 926
Josh Withee Avatar asked Oct 16 '25 10:10

Josh Withee


1 Answers

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);
like image 114
Nina Scholz Avatar answered Oct 19 '25 00:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!