 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Applying f(x) to each array element in JavaScript
Problem
Suppose, a mathematical function given by −
f(x) = ax2 + bx + c
Where a, b and c are three constants.
We are required to write a JavaScript function that takes in a sorted array of Integers, arr as the first argument and a, b and c as second, third and fourth argument. The function should apply the function f(x) to each element of the array arr.
And the function should return a sorted version of the transformed array.
For example, if the input to the function is −
const arr = [-8, -3, -1, 5, 7, 9]; const a = 1; const b = 4; const c = 7;
Then the output should be −
const output = [ 4, 4, 39, 52, 84, 124 ];
Example
The code for this will be −
const arr = [-8, -3, -1, 5, 7, 9]; const a = 1; const b = 4; const c = 7; const applyFunction = (arr = [], a = 1, b = 1, c = 1) => {    const apply = (num, a, b, c) => {       const res = (a * (num * num)) + (b * num) + (c);       return res;    };    const result = arr.map(el => apply(el, a, b, c));    result.sort((a, b) => a - b);    return result; }; console.log(applyFunction(arr, a, b, c)); Code Explanation:
We first mapped over the array to apply the f(x) function to each element and then sorted the array using the Array.prototype.sort() and then finally returned the sorted array.
Output
The output in the console will be −
[ 4, 4, 39, 52, 84, 124 ]
Advertisements
 