Applying f(x) to each array element in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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 ]
raja
Published on 18-Mar-2021 09:12:08
Advertisements