JavaScript
JavaScript Array Type
Map
JavaScript provides the map method to transform all of the elements
of an array by applying a given function on them. map returns a new
array with transformation applied. The transformation can be
customized by specifying a callback function. The callback function
should accept a value from the array and return a single transformed
value back.
const c2f = c => (c * 9 / 5) + 32const temps = [20, 16, 32]const tempsF = temps.map(c2f)console.log(temps) // [20, 16, 32]console.log(tempsF) // [68, 60.8, 89.6]
Code example: indexes
["a", "b", "c"].map((el, i) => `${i} : ${el}`)// ["0 : a", "1 : b", "2 : c"]
The map method passes the index to the callback function as well,
and we can use this in our transformations if we want to.
Code example: plus one
const nums = [1, 2, 3]const oneMore = nums.map(n => n + 1)console.log(nums) // [2, 3, 4]
Code example: re-implementation of map
const myMap = (arr, fn) => {const result = []arr.forEach(el => result.push(fn(el)))return result}
The above re-implementation of map is not equivalent to the
Array.prototype.map method, but it shows the basic concept.
Read more on MDN
Array.prototype.map()
Test yourself
Description
Define a new function with the name
sumOfSquares
that takes an integer array input parameter arr and returns a new
array with the sum of the squares of all the elements.
Assumptions:
- All elements of the input array are integer numbers.
Tips:
- Transform the input array into an array of squares.
- Calculate the sum of the array of squares by iterating through it.
Tests
- 1
You should define a function named
sumOfSquares. - 2
sumOfSquares([])should return0. - 3
sumOfSquares([100,200,300])should return140000. - 4
sumOfSquares([1,2,3,4])should return30. - 5
sumOfSquares([-1,2,-3,4])should return30.