
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inverting Signs of Integers in an Array Using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers (negatives and positives).
Our function should convert all positives to negatives and all negatives to positives and return the resulting array.
Example
Following is the code −
const arr = [5, 67, -4, 3, -45, -23, 67, 0]; const invertSigns = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(+el && el !== 0){ const inverted = el * -1; res.push(inverted); }else{ res.push(el); }; }; return res; }; console.log(invertSigns(arr));
Output
[ -5, -67, 4, -3, 45, 23, -67, 0 ]
Advertisements