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?

nickf
548k199 gold badges660 silver badges727 bronze badges
asked Jun 8, 2012 at 7:49
3
  • Do you have myarray[0] and my2ndarray[0]? E.g. Are there duplicate keys? Commented Jun 8, 2012 at 7:51
  • Yes, it's possible, what have you tried? Commented Jun 8, 2012 at 7:51
  • 1
    yes it is, you just did :) why cant you just loop those arrays? Commented Jun 8, 2012 at 7:51

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('&');
answered Jun 8, 2012 at 7:54
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

answered Jun 8, 2012 at 7:55

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.

answered Jun 8, 2012 at 7:54

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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.