- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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