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