Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Using Array.reduce() Method
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
{ positive: [ 97, 13, 133, 32, 33 ], negative: [ -108, -12, -887, -15, -77 ] }
Using Array.filter() Method
An alternative approach using separate filter operations:
const arr = [97, -108, 13, -12, 133, -887, 32, -15, 33, -77];
const splitArrayWithFilter = (arr) => {
return {
positive: arr.filter(num => num >= 0),
negative: arr.filter(num => num
{ positive: [ 97, 13, 133, 32, 33 ], negative: [ -108, -12, -887, -15, -77 ] }
Handling Zero Values
Note that zero (0) is treated as positive in these examples. If you need different handling:
const arrWithZero = [5, -3, 0, -8, 12];
const splitWithZeroHandling = (arr) => {
return arr.reduce((acc, val) => {
if (val > 0) {
acc['positive'].push(val);
} else if (val
{ positive: [ 5, 12 ], negative: [ -3, -8 ], zero: [ 0 ] }
Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
reduce() |
Single pass | Moderate | Lower |
filter() |
Two passes | Higher | Higher |
Conclusion
The reduce() method is more efficient as it processes the array in a single pass, while filter() offers better readability. Choose based on your performance needs and code clarity preferences.
