
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
Make Array Numbers Negative in 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 ]
Advertisements