
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- 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 false objects to bottom in JavaScript
- Pushing elements to a Stack in Javascript
- Removing Negatives from Array in JavaScript
- Separate Odd and Even Elements into Two Separate Arrays in Java
- Count groups of negatives numbers in JavaScript
- Converting a comma separated string to separate arrays within an object JavaScript
- Sum of all positives present in an array in JavaScript
- Pushing NaN to last of array using sort() in JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- Separate odd and even in JavaScript
- AND product of arrays in JavaScript
- Comparing and filling arrays in JavaScript
- Merging and rectifying arrays in JavaScript

Advertisements