Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Constructing an array of addition/subtractions relative to first array element in JavaScript
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 −
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' ]
Advertisements
