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

JavascriptWeb DevelopmentFront End Technology

Problem

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.

For example

[4, 3, 6, 2]

should return −

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

Example

Following is the code −

 Live Demo

const arr = [4, 3, 6, 2];
const buildRelative = (arr = []) => {
   const res = [];
   let num = '';
   for(let i of arr){
      if(i - arr[0] >= 0){
         num += '+' + (i - arr[0])
      }else{
         num += i - arr[0]
      };
      res.push(num);
      num = '';
   };
   return res;
};
console.log(buildRelative(arr));

Output

[ '+0', '-1', '+2', '-2' ]
raja
Published on 21-Apr-2021 10:25:23
Advertisements