- 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
Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
We have to write a function that takes in an array and returns an object with two properties namely positive and negative. They both should be an array containing all positive and negative items respectively from the array.
This one is quite straightforward, we will use the Array.prototype.reduce() method to pick desired elements and put them into an object of two arrays.
Example
const arr = [ [12, -45, 65, 76, -76, 87, -98], [54, -65, -98, -23, 78, -9, 1, 3], [87, -98, 3, -2, 123, -877, 22, -5, 23, -67] ]; const splitArray = (arr) => { return arr.reduce((acc, val) => { if(val < 0){ acc['negative'].push(val); } else { acc['positive'].push(val); } return acc; }, { positive: [], negative: [] }) }; for(let i = 0; i < arr.length; i++){ console.log(splitArray(arr[i])); }
Output
The output in the console will be −
{ positive: [ 12, 65, 76, 87 ], negative: [ -45, -76, -98 ] } { positive: [ 54, 78, 1, 3 ], negative: [ -65, -98, -23, -9 ] } { positive: [ 87, 3, 123, 22, 23 ], negative: [ -98, -2, -877, -5, -67 ] }
- Related Articles
- Looping numbers with object values and push output to an array - JavaScript?
- Reversing negative and positive numbers in JavaScript
- Make array numbers negative JavaScript
- Distinguish positive and negative numbers.
- Recursion in array to find odd numbers and push to new variable JavaScript
- Implement Bubble sort with negative and positive numbers – JavaScript?
- How can I split an array of Numbers to individual digits in JavaScript?
- Difference between numbers and string numbers present in an array in JavaScript
- Lambda expression in Python to rearrange positive and negative numbers
- Removal of negative numbers from an array in Java
- Explain the difference between positive and negative numbers.
- Positive, negative and zeroes contribution of an array in JavaScript
- How to separate alphabets and numbers from an array using JavaScript
- Golang Program to Print the Sum of all the Positive Numbers and Negative Numbers in a List
- Python program to count positive and negative numbers in a list

Advertisements