-4

To be specific: Let consider this array -

var strings = ['John', 'Jane', 'Mary'];

Now the question is how can I add something to that existing element in array like I want to append |Teacher in John so that it would be John|Teacher.

So altogether, I want is -

var strings = ['John|Teacher', 'Jane|Doctor', 'Mary|Housekeeper'];

How can I do this? Please help.

6
  • 1
    Iterate over the array and append |Teacher to every element. Use a for loop or the Array.map function to iterate over elements. Commented Oct 30, 2017 at 15:16
  • Get the content of the array at index i, modify the string, store the value back at index i Commented Oct 30, 2017 at 15:16
  • The question is unclear. When do you want to add Teacher, Doctor, Housekeeper ? Commented Oct 30, 2017 at 15:17
  • 4
    sounds like you would be better off with a different model Commented Oct 30, 2017 at 15:18
  • Possible duplicate of Modify Javascript Array Element Commented Oct 30, 2017 at 15:35

1 Answer 1

2

Try this:

var strings1 = ['John', 'Jane', 'Mary'];
var strings2 = ['Teacher', 'Doctor', 'Housekeeper'];
var strings = strings1.map(function(e, i) {return e + '|' + strings2[i];});
Sign up to request clarification or add additional context in comments.

6 Comments

Awesome. Also did it with forEach! Thanks a lot.
Why are you returning an Array from the map callback?
@llama: Returning the array that this dude was asking for.
@goodvibration: Where? Looks to me like the result should be an array of strings, not an array of arrays that have a single string. His result: ['John|Teacher', 'Jane|Doctor', 'Mary|Housekeeper']; Your result: [['John|Teacher'], ['Jane|Doctor'], ['Mary|Housekeeper']];
@llama: Oh well, I just "alerted" the results, so probably missed that. You can simply remove the [ and ] (which I just did myself).
|

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.