0

I am trying to use map to cast this string to an array of objects. instead I get a result of undefined for each element. What am I missing here?

const sample = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

function solve(puzzle) {
    puzzle = puzzle.split('').map(x=>{value:x})
    console.log(puzzle)
}

solve(sample)
eleethesontai
  • 454
  • 5
  • 19
  • also: [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions#:~:text=Arrow%20functions%20allow%20you%20to,to%20use%20the%20return%20keyword.&text=This%20should%20be%20the%20correct,expression's%20value%20is%20returned%20implicitly.) – pilchard Mar 30 '23 at 14:13
  • MDN [(code) block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block) and [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label) – Thomas Mar 30 '23 at 14:35

1 Answers1

1

In this line puzzle = puzzle.split('').map(x=>{value:x}) you forgot to open and close an extra ()

Also it is a bad practice to use .map() if you are not gonna use the new array it creates, so I changed that as well

const sample = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'

function solve(puzzle) {
    const res = puzzle.split('').map(x=>({value:x}))
    return res;
}

console.log(solve(sample));
Chris G
  • 1,598
  • 1
  • 6
  • 18
  • 1
    What's that about bad practice? OP *is* using the returned array… – deceze Mar 30 '23 at 13:52
  • 1
    It's not as pretty, but it's faster if you do: `const res = Array.prototype.map.call(puzzle, (x)=>({value:x}))`. It just puts a gun to Array#map's head and tells it to use the string as `this`. The string looks so array-like, it works. – doug65536 Mar 30 '23 at 13:55
  • he is overwriting puzzle with .map, not creating a new array to return that. `.map()` is not meant to be used to mutate the original array. – Chris G Mar 30 '23 at 13:56
  • 2
    `map` *isn't* "mutating" the original array. It's creating a *new* array. That just gets assigned to the same variable in the end, but that's not *mutating* the original array. I know what bad practice you're referring to, but this ain't a case of that. – deceze Mar 30 '23 at 14:09