
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
Push Positives and Negatives to Separate Arrays in JavaScript
We are required to write a function that takes in an array and returns an object with two arrays positive and negative. They both should be containing all positive and negative items respectively from the array.
We will be using the Array.prototype.reduce() method to pick desired elements and put them into an object of two arrays.
Example
The code for this will be −
const arr = [97, -108, 13, -12, 133, -887, 32, -15, 33, -77]; const splitArray = (arr) => { return arr.reduce((acc, val) => { if(val < 0){ acc['negative'].push(val); }else{ acc['positive'].push(val); } return acc; }, { positive: [], negative: [] }) }; console.log(splitArray(arr));
Output
The output in the console −
{ positive: [97, 13, 133, 32, 33,], negative: [ -108, -12, -887, -15, -77 ] }
Advertisements