0

I'm new to js and have this task that confuses the hell out of me.

The task is to "use Array.map() to create a new array that contains the last digit of all prime numers". I already have an array 'primes' containing the prime numbers.

It actually works fine if I only want to print the last digit for each item of the primes array using console.log:

let lastDig = new Array()
lastDig = primes.map((value, index) => console.log(value % 10))
// -> 2,3,5,7,1,3,7,...

However, if I try to then add the digit to the array I'm supposed to fill in the task, it just ends up filling it with 1,2,3,4,5,..., 25, even though the ONLY thing I changed in the code was to replace console.log(value % 10) by lastDig.push(value % 10).

let lastDig = new Array()
lastDig = primes.map((value, index) => lastDig.push(value % 10))
// -> lastDig contains: 1,2,3,4,5,..., 25

How can I make this work and why does it change the values if I barely changed the code?

3
  • I don't think you want the " lastDig = " in the line, " lastDig = primes.map((value, index) => lastDig.push(value % 10)) Commented Oct 21, 2022 at 16:19
  • @Aadmaa: That may work, but would leave unintuitive code. .map() returns a new array and it's generally expected that its return value is the intended result of the operation. Relying on .push() in this way instead should probably be done with a normal loop, not with .map(). Commented Oct 21, 2022 at 16:30
  • @David - true; that method would look better with the array's forEach() method. But your answer below looks best to me too. Commented Oct 21, 2022 at 16:50

1 Answer 1

3

You're trying to create the array in two different ways simultaneously.

.map() returns an array, composed of what each element was projected into as the return value of the map callback function. So don't try to push the value as the operation in the map callback, simply return it:

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
let lastDig = primes.map(value => value % 10);
console.log(lastDig);

What's happening in your code is all of those .push() operations are essentially rendered moot when you assign the return value of .map() to lastDig. And that return value is an array of what each .push() operation returned, which was the new length of the array each time.

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

1 Comment

good answer, also if you want to generate a primes variable you can create a function that returns first the array and then map it with the @David answer. for the function see here stackoverflow.com/q/21966000/17716837

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.