Applying f(x) to each array element in JavaScript

When working with arrays in JavaScript, you often need to apply mathematical functions to each element and return a sorted result. This article demonstrates how to apply a quadratic function f(x) = ax² + bx + c to array elements.

Problem Statement

Given a mathematical function:

f(x) = ax² + bx + c

Where a, b, and c are constants, we need to create a JavaScript function that:

  • Takes a sorted array of integers as the first argument
  • Takes constants a, b, and c as the next three arguments
  • Applies f(x) to each array element
  • Returns the transformed array in sorted order

Example Input and Output

For the input:

const arr = [-8, -3, -1, 5, 7, 9];
const a = 1, b = 4, c = 7;

The expected output is:

[4, 4, 39, 52, 84, 124]

Solution Implementation

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));
[4, 4, 39, 52, 84, 124]

Step-by-Step Calculation

Let's verify the calculation for each element:

const calculateSteps = (arr, a, b, c) => {
    arr.forEach(x => {
        const result = a * (x * x) + b * x + c;
        console.log(`f(${x}) = ${a}(${x})² + ${b}(${x}) + ${c} = ${result}`);
    });
};

calculateSteps([-8, -3, -1, 5, 7, 9], 1, 4, 7);
f(-8) = 1(-8)² + 4(-8) + 7 = 39
f(-3) = 1(-3)² + 4(-3) + 7 = 4
f(-1) = 1(-1)² + 4(-1) + 7 = 4
f(5) = 1(5)² + 4(5) + 7 = 52
f(7) = 1(7)² + 4(7) + 7 = 84
f(9) = 1(9)² + 4(9) + 7 = 124

Alternative Approach with Method Chaining

const applyFunctionChained = (arr = [], a = 1, b = 1, c = 1) => {
    return arr
        .map(x => a * x * x + b * x + c)
        .sort((x, y) => x - y);
};

const arr2 = [-2, 0, 2, 4];
console.log(applyFunctionChained(arr2, 1, -2, 1));
[-3, 1, 1, 9]

How It Works

The solution uses two key array methods:

  • Array.map() - Transforms each element by applying the quadratic function
  • Array.sort() - Sorts the transformed values in ascending order

The inner apply function calculates f(x) = ax² + bx + c for each element, then the result array is sorted numerically.

Conclusion

This approach efficiently applies mathematical functions to array elements using map() for transformation and sort() for ordering. The pattern works for any mathematical function that needs to be applied element-wise to arrays.

Updated on: 2026-03-15T23:19:00+05:30

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements