Higher-Order Function Demo - Problem

Create a function that takes an array and a callback function, applying the callback to each element and returning a new array with the transformed results.

The callback function will be passed as a string representation that you need to evaluate. Common callback operations include:

  • x => x * 2 (double each element)
  • x => x + 1 (add 1 to each element)
  • x => x * x (square each element)

Your function should iterate through the array, apply the callback to each element, and return the new transformed array.

Input & Output

Example 1 — Double Each Element
$ Input: arr = [2, 4, 6], callback = "x => x * 2"
Output: [4, 8, 12]
💡 Note: Apply doubling function to each element: 2*2=4, 4*2=8, 6*2=12
Example 2 — Add One to Each
$ Input: arr = [1, 3, 5], callback = "x => x + 1"
Output: [2, 4, 6]
💡 Note: Apply increment function to each element: 1+1=2, 3+1=4, 5+1=6
Example 3 — Square Each Element
$ Input: arr = [2, 3, 4], callback = "x => x * x"
Output: [4, 9, 16]
💡 Note: Apply squaring function to each element: 2²=4, 3²=9, 4²=16

Constraints

  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000
  • callback is a valid function string

Visualization

Tap to expand
Higher-Order Function DemoINPUTArray: [2, 4, 6]246Callback Function:x => x * 2ALGORITHM STEPS1Parse callback: x * 22Apply to element 2: 2 * 2 = 43Apply to element 4: 4 * 2 = 84Apply to element 6: 6 * 2 = 12FINAL RESULTTransformed Array:4812[4, 8, 12]Key Insight:Higher-order functions enable code reusability by treating functions as first-classvalues that can be passed as parameters and applied to transform data.TutorialsPoint - Higher-Order Function Demo | Optimized Function Creation
Asked in
Google 25 Meta 20 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen