1

In python, you can do:

ints = [1, 2, 3]
str_ints = [str(my_int) for my_int in ints]
print(str_ints)

which outputs:

['1', '2', '3']

I want to do something similar using javascript using forEach,

let ints = [1, 2, 3]
str_ints = [ints.forEach(my_int => {return String(my_int)})]
console.log(str_ints)

I would expect the output to be:

Array ['1', '2', '3']

however, the output is

Array[undefined]

Is this sort of array creation not possible in javascript?

2
  • 2
    Why do you want to use forEach instead of functionality designed for the task you want? Commented May 12, 2019 at 21:37
  • 1
    Another way to simulate array comprehension in JS - stackoverflow.com/questions/45310911/… Commented May 12, 2019 at 21:40

1 Answer 1

4

That's called mapping, and here's how you do it in JavaScript:

var ints = [1, 2, 3];
var str_ints = ints.map((i) => String(i));
console.log(str_ints);

As suggested by @OriDrori, you can omit the arrow function:

var ints = [1, 2, 3];
var str_ints = ints.map(String);
console.log(str_ints);

Sign up to request clarification or add additional context in comments.

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.