skip to Main Content

I’m trying to Transform Array values using the map method and print out values using the console.

function transformToObjects(numberArray) {

  return numberArray.map((number) => {
    return { val: number };
  });
}

I tried to print out the array values using console.log(numberArray); but the browser keep showing "ReferenceError".

The expected outcome should look like this:

{val: 1}, {val: 2}, {val: 3}

2

Answers


  1. You’re encountering is that you’re trying to print the numberArray directly after the map operation, but the numberArray itself is not modified by the map method. Instead, the map method returns a new array with the transformed values.

    function transformToObjects(numberArray) {
      const transformedArray = numberArray.map((number) => {
        return { val: number };
      });
    
      console.log(transformedArray);
    }
    
    // For test
    const numbers = [1, 2, 3];
    transformToObjects(numbers);
    Login or Signup to reply.
  2. Try this

    function transformToObjects(numberArray) {
      const transformedArray = numberArray.map((number) => {
        return { val: number };
      });
    
      console.log(transformedArray);
      return transformedArray;
    }
    // For test
    const numbers = [1, 2, 3];
    transformToObjects(numbers);
    console.log(transformToObjects(numbers));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search