- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 ]
- Related Articles
- Inverting signs in array - JavaScript
- Returning reverse array of integers using JavaScript
- How to create an array of integers in JavaScript?
- How to sort an array of integers correctly in JavaScript?
- How to sort an array of integers correctly JavaScript?
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Inverting a binary tree in JavaScript
- Inverting slashes in a string in JavaScript
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- Finding astrological signs based on birthdates using JavaScript
- Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
- Store count of integers in order using JavaScript
- Adding an element in an array using Javascript
- Finding product of an array using recursion in JavaScript
- Maximum length of mountain in an array using JavaScript

Advertisements