Experimenting with the rest operator-custom challenge

I was trying to get the folowing array writing the least amount of code possible and, ideally, using the spread operator.

[ [‘J’, ‘A’, 'N] , [‘F’, ‘E’, ‘B’], [‘M’, ‘A’, ‘R’], [‘A’, ‘P’, ‘R’], [‘M’, ‘A’, ‘Y’] ]

The code you see is simply me trying to “get a feel” for the spread operator.

The first thing I tried was the very naive approach:

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
console.log( ...[...arr1]) 

which spits out the same thing as

console.log(...arr1) 

If I try

console.log(...(...arr1))

I get an error.

Could someone give me a hint?

Link to the challenge:

Basiacally, you want a new array where each element of the old array (strings) become new elements (arrays of strings, based on the corresponding old element). That is a classic case for a map method.

1 Like

Yes, I was able to get the result you wanted with map and using a spread operator. What did you come up with?

Me too, here’s my code for anyone interested:

console.log(arr1.map(n => [...n]));

Now I am trying to get the single letters (starting from the same input and using the least amount of code).
I want the output to be [‘J’, ‘A’, ‘N’, ‘F’, ‘E’, ‘B’, ‘M’, ‘A’, ‘R’ and so on]

I added [spoiler][/spoiler] tags to your post, since that seemed to be what you want.

Cool, that is the exact solution I came up with.

… using the least amount of code

That can be a fun exercise but just be warned that sometimes the best code is not the shortest. Readability and maintainability are often more important than saving a few lines of code. I think “simple” is a good goal, as long as “easy to read” is factored in. Well written code reads like a story and explains itself.

I want the output to be [‘J’, ‘A’, ‘N’, ‘F’, ‘E’, ‘B’, ‘M’, ‘A’, ‘R’ and so on]

I was able to do with with a reduce method and a few spread operators. I’m not seeing anything simpler.

a loop and push method + spread works fine for me

Sure, I guess that would be “simpler” for learners uncomfortable with reduce. It’s doing the same thing, just that reduce does it in a single line and I think it’s a “better” solution. I think a properly applied method is always better than a loop - assuming it doesn’t get too arcane. But I would definitely agree that the loop method is a better place to start if that solution is not clear.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.