

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Pushing 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 ] }
- Related Questions & Answers
- Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
- What are False Positives and True Positives in Cybersecurity?
- Pushing elements to a Stack in Javascript
- Pushing false objects to bottom in JavaScript
- Removing Negatives from Array in JavaScript
- Separate odd and even in JavaScript
- Converting a comma separated string to separate arrays within an object JavaScript
- Count groups of negatives numbers in JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- Pushing NaN to last of array using sort() in JavaScript
- Sum of all positives present in an array in JavaScript
- Split keys and values into separate objects - JavaScript
- How to separate alphabets and numbers from an array using JavaScript
- AND product of arrays in JavaScript
- Comparing and filling arrays in JavaScript
Advertisements