Home > Mobile >  Javascript arrow function doesn't work as expected, working on an array using Array.map, arrays
Javascript arrow function doesn't work as expected, working on an array using Array.map, arrays

Time:10-25

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?

CodePudding user response:

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.

  • Related