Constructing an array of addition/subtractions relative to first array element in JavaScript

We are required to write a JavaScript function that takes in an array of positive integers. Our function should map this array to an array of string integers.

The array should contain the number we should add/subtract to the first element to achieve the corresponding element.

Problem

For example, if we have:

[4, 3, 6, 2]

We need to calculate the difference between each element and the first element (4):

  • 4 - 4 = 0 ? "+0"
  • 3 - 4 = -1 ? "-1"
  • 6 - 4 = 2 ? "+2"
  • 2 - 4 = -2 ? "-2"

The result should be:

['+0', '-1', '+2', '-2']

Solution

const arr = [4, 3, 6, 2];

const buildRelative = (arr = []) => {
    const res = [];
    const firstElement = arr[0];
    
    for (let i = 0; i < arr.length; i++) {
        const difference = arr[i] - firstElement;
        
        if (difference >= 0) {
            res.push('+' + difference);
        } else {
            res.push('' + difference);
        }
    }
    
    return res;
};

console.log(buildRelative(arr));
['+0', '-1', '+2', '-2']

Alternative Solution Using map()

We can make the code more concise using the map() method:

const arr = [4, 3, 6, 2];

const buildRelative = (arr = []) => {
    const firstElement = arr[0];
    
    return arr.map(num => {
        const difference = num - firstElement;
        return difference >= 0 ? '+' + difference : '' + difference;
    });
};

console.log(buildRelative(arr));
['+0', '-1', '+2', '-2']

How It Works

The function works by:

  1. Storing the first element as our reference point
  2. Iterating through each element in the array
  3. Calculating the difference between each element and the first element
  4. Adding a "+" prefix for non-negative differences
  5. Negative differences automatically include the "-" sign

Conclusion

This approach efficiently transforms an array into relative differences from its first element. The map() method provides a cleaner, more functional programming approach.

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

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements