user4381753 user4381753 - 6 months ago 10
PHP Question

Combine each element of a string with the second string

I have 2 strings

[a,b,c] //there could be any number of items in these 2 strings
[x,y,z]


I want an output like this

a[x,y,z]
b[x,y,z]
c[x,y,z]


Not quite able to get the logic to get the output.

Answer

To get as an array use map()

var s1 = '[a,b,c]',
  s2 = '[x,y,z]';
console.log(
  s1
  .slice(1, -1) // remove the `[` and `[`
  .split(',') // split based on `,`
  .map(function(a) { // iterate and generate array
    return a + s2;
  })
)


To get as a string use reduce()

var s1 = '[a,b,c]',
  s2 = '[x,y,z]';
console.log(
  s1
  .slice(1, -1) // remove `[` and `]`
  .split(',') // split based on `,`
  .reduce(function(a, b) { // iterate and generate string
    return a + (a.length ? '\n' : ' ') + b + s2;
  }, '')
)