0

Hello i have 2 arrays and and i want to put them in a single string. My arrays can take values from 0 to a maxNum-1. So lets say i have myArray1[i] and myArray2[i] I want to make a string like this:

string = "myArray1ID" + 1 + "=" + (myArray1[1])
    + "&" +"myArray2ID" + 1 + "=" + (myArray2[1])
    + "&" + "myArray1ID" + 2 + "=" + (myArray1[2])
    + "&" + "myArray2ID" + 2 + "=" + (myArray2[2])
    + ......
    + "myArray1ID" + (maxNum - 1) + "=" + (myArray[maxNum-1])
    + "&" "myArray2ID" + (maxNum - 1) + "=" + (myArray2[maxNum-1]);

Is it possible?

3

3 Answers 3

3

Use the power of loops.

var output = [];

for (var i = 1; i < maxNum; ++i) {
    output.push(
        'myArray1ID' + i + '=' + myArray1[i],
        'myArray2ID' + i + '=' + myArray2[i]
    );
}
return output.join('&');
Sign up to request clarification or add additional context in comments.

Comments

1
var myString = '';

for(var i; i < myArray1.length; i++){
  myString += "myArray1ID" + i + "=" + (myArray1[i]) + "&";
  myString += "myArray2ID" + i + "=" + (myArray2[i]) + "&";
}

//remove trialing "&"
var myString = myString.substring(0, myString.length-1);

This assumes that both arrays are of equal length

Comments

0

Use a loop :

var stringArray = sep = ""; 
for(var i = 1; i < maxNum; i++) {
    stringArray += sep + "myArray1ID" + i + "=" + myArray1[i];
    stringArray += "&myArray2ID" + i + "=" + myArray2[i];
    sep = "&";
}

The var stringArray should contains your array values.

1 Comment

In this example, the variable 'sep' will be leaked to the global scope. Unless that's your intention, the two variables 'stringArray' and 'sep' should be defined individually. Also, nickf's answer will be more performant, array operations are generally faster than string concatenation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.