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 ]
}

Updated on: 21-Aug-2020

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements