- 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
Make array numbers negative JavaScript
Let’s say, the following is our array −
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6];
We are required to write a function that takes in the above array and returns an array with all the corresponding elements of array change to their negative counterpart (like 4 to -4, 6 to -6).
If the element is already negative, then we should leave the element unchanged. Let’s write the code for this function −
Example
const arr = [7, 2, 3, 4, 5, 7, 8, 12, -12, 43, 6]; const changeToNegative = (arr) => { return arr.reduce((acc, val) => { const negative = val < 0 ? val : val * -1; return acc.concat(negative); }, []); }; console.log(changeToNegative(arr));
Output
The output in the console will be −
[ -7, -2, -3, -4, -5, -7, -8, -12, -12, -43, -6 ]
- Related Articles
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Make numbers in array relative to 0 – 100 in JavaScript
- Reversing negative and positive numbers in JavaScript
- Removal of negative numbers from an array in Java
- Implement Bubble sort with negative and positive numbers – JavaScript?
- Negative Binary Numbers
- Splitting a hyphen delimited string with negative numbers or range of numbers - JavaScript?
- What is negative numbers ?
- Positive, negative and zeroes contribution of an array in JavaScript
- Prevent negative numbers in MySQL?
- Distinguish positive and negative numbers.
- What are the negative numbers?
- Can negative numbers be prime?
- Are array of numbers equal - JavaScript
- Modulus of Negative Numbers in C

Advertisements