Array.prototype.map() did not work correctly

Viewed 202

/*
Write a function called doubleValues which accepts an array and returns a new array with all the values in the array passed to the function doubled

Examples:
    doubleValues([1,2,3]) // [2,4,6]
    doubleValues([5,1,2,3,10]) // [10,2,4,6,20]

*/

function doubleValues(array){
     return array.map(function(value) {
         return value * 2;
        })
    }

// describe("#doubleValues", function() {
//   it("doubles values in an array", function() {
//     expect(doubleValues([1, 2, 3])).toEqual([2, 4, 6]);
//   });
//   it("works for negative numbers", function() {
//     expect(doubleValues([1, -2, -3])).toEqual([2, -4, -6]);
//   });
// });
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine-html.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/boot.js"></script>
    <script type="text/javascript" src="foreach-map-filter.js"></script>
    <script type="text/javascript" src="foreach-map-filter.test.js"></script>
  </head>
  <body>

  </body>
</html>

The problem requires me to Write a function called doubleValues which accepts an array and returns a new array with all the values in the array passed to the function doubled

Examples: doubleValues([1,2,3]) // [2,4,6] doubleValues([5,1,2,3,10]) // [10,2,4,6,20]

Why doesn't my function work? Feels like I used the lecturer's code template verbatim. Any help is appreciated.

function doubleValues(array){
     return array.map(function(value) {
         return value * 2;
        })
    }

3 Answers

You may not be calling the function, it works. Can you try below code.

function doubleValues(array){
     return array.map(function(value) {
         return value * 2;
        })
    }
    const result=doubleValues([1,2,3])
    console.log(...result);

Here is the working example:

var array = [2,5,8,9];
function doubleValues(arr){
     return arr.map((value) => value * 2);
     
}
    
console.log(doubleValues(array));

function doubleValues(array){
     return array.map(x => x * 2);
    }

I don't know why you use function(value) in map function.

Related