Home > Net >  Combine two strings/arrays
Combine two strings/arrays

Time:01-13

I am not sure if want I want is possible.

string1= Blue | Green  | Violet  | Pink

string2= light  | dark  | smooth  | light

I need =

Blue light | Green dark  | Violet smooth  | Pink light

CodePudding user response:

There you go. An easy solution using latest JS features like .reduce

const firstElements = 'Blue | Green  | Violet  | Pink'.split('|');

const secondElements = 'light  | dark  | smooth  | light'.split('|');

let result = firstElements.reduce((accumulator, currentValue, index) => {
  let divider = '|';
  if (!secondElements[index   1]) {
    divider = ''
  }
  return accumulator  = ` ${currentValue.trim()} ${secondElements[index].trim()} ${divider}`;

}, "").trim();

console.log(result)

CodePudding user response:

If you are meaning about all:

  • string1 is one of Blue, Green, Violet, or Pink
  • string2 is one of light, dark, smooth, or light
  • expecting concat them

then, you can string1 string2.

Or, do you mean for arrays?:

const strings1 = ["Blue", "Green", "Violet", "Pink"];
const strings2 = ["light", "dark", "smooth", "light"];
// ["Blue light", "Green dark", "Violet smooth", "Pink light"]
const result = strings1.map((string, index) => [string, strings2[index]])

CodePudding user response:

What you want to do is split the strings, then iterate through and combine them. It ends up looking like something like this:

// Create strings
var string1 = "Blue | Green  | Violet  | Pink";
var string2 = "light  | dark  | smooth  | light";
var string3 = "";

// Create arrays
var arr1 = string1.split(' | ');
var arr2 = string2.split(' | ');
var arr3 = [];

// Iterate through
for(var i = 0; i < arr1.length; i  ){
  arr3.push(arr1[i]   ' '   arr2[i]);
}

// Join array
var string3 = arr3.join(' | ');
console.log(string3);

  •  Tags:  
  • Related