1

Could someone please help me do the following with JavaScript:

  • I have an array (array1) that contains strings
  • I need to loop through each element of the initial array (array1)
  • then I need to get the value of each index in array1, and add a letter to each value
  • and finally to write the modified value of each index from array1 into array2.

Thank you.

2
  • 3
    What have you tried? Commented Feb 8, 2013 at 23:58
  • Array.map is a good start Commented Feb 9, 2013 at 0:08

2 Answers 2

2
//declares the array and initializes it with strings
var array1 = ["one", "two", "three", "four"];

//declares the second array
var array2 = []; 

//this line begins the loop. Everything inside the { } will run once for every single item inside array1
for (var i = 0; i < array1.length; i++) 
{
    //this gets the contents of the array at each interval
    var string = array1[i]; 

    //here we take the original string from the array1 and add a letter to it.
    var combo = string + "A"; 

    //this line takes the new string and puts it into the 2nd array
    array2.push(combo); 
}

//displays a message box that shows the contents of the 2nd array
alert(array2); 
Sign up to request clarification or add additional context in comments.

Comments

0

Example using Array.map.

var singularArray = ['Dog', 'Cat', 'Bird'],
pluralArray = singularArray.map(function(value){
    return value+'s';
});

console.log(pluralArray); //Logs ['Dogs', 'Cats', 'Birds']

http://jsfiddle.net/fzakf/

See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map for details.

Comments

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.