Talentd
FleetCode

2635. Apply Transform Over Each Element in Array

Easy86.0% acceptance3 companies

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.

Example 1:

Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one. 

Example 2:

Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.

Example 3:

Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.

Constraints:

  • 0 <= arr.length <= 1000
  • -109 <= arr[i] <= 109
  • fn returns an integer.

Asked at 3 companies

Hints open one at a time

Hint 1
Start by creating an array that will eventually be returned.
Hint 2
Loop over each element in the passed array. Push fn(arr[i]) to the returned array.
6:58
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @param {number[]} arr
3 * @param {Function} fn
4 * @return {number[]}
5 */
6var map = function(arr, fn) {
7
8};
Starter codeJavaScriptSpaces: 4
Examples
Input
function plusone(n) { return n + 1; }
[1,2,3]
Input
function plusI(n, i) { return n + i; }
[1,2,3]
Input
function constant(n, i) { return 42; }
[10,20,30]
Your code is saved on this device.Solution