-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.

Sanjay
  • 540
  • 2
  • 13
  • 29
  • 1
    Iterate over the array and append |Teacher to every element. Use a `for` loop or the `Array.map` function to iterate over elements. – bamtheboozle Oct 30 '17 at 15:16
  • Get the content of the array at index `i`, modify the string, store the value back at index `i` – Andreas Oct 30 '17 at 15:16
  • The question is unclear. When do you want to add `Teacher`, `Doctor`, `Housekeeper` ? – yuantonito Oct 30 '17 at 15:17
  • 4
    sounds like you would be better off with a different model – epascarello Oct 30 '17 at 15:18
  • Possible duplicate of [Modify Javascript Array Element](https://stackoverflow.com/questions/29924905/modify-javascript-array-element) – Maxim Oct 30 '17 at 15:35
  • Possible duplicate of [How to append something to an array?](https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array) – Aluan Haddad Oct 30 '17 at 16:48

1 Answers1

2

Try this:

var strings1 = ['John', 'Jane', 'Mary'];
var strings2 = ['Teacher', 'Doctor', 'Housekeeper'];
var strings = strings1.map(function(e, i) {return e + '|' + strings2[i];});
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • 1
    Awesome. Also did it with forEach! Thanks a lot. – Sanjay Oct 30 '17 at 15:29
  • Why are you returning an Array from the map callback? – llama Oct 30 '17 at 15:37
  • @llama: Returning the array that this dude was asking for. – goodvibration Oct 30 '17 at 15:40
  • @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 Oct 30 '17 at 15:42
  • @llama: Oh well, I just "alerted" the results, so probably missed that. You can simply remove the `[` and `]` (which I just did myself). – goodvibration Oct 30 '17 at 15:44
  • @llama Good eye there. But fixed it :) – Sanjay Oct 30 '17 at 16:09