简体   繁体   中英

How to print two array lists in an object in JavaScript

I have an array like var myArr = [0,-1,2,-3,4,-5,6];

I want to separate all positive No's and negative No's in array format like

positiveArr = [0,2,4,6] and negativeArr = [-1,-3,-5] .

Then like to print both arrays in object format.

Final expected result something like an object:

{Positive: [0,2,4,6], Negative: [-1,-3,-5]}

Thanks.

You can do it with the help of Array.prototype.reduce :

 const myArr = [0,-1,2,-3,4,-5,6]; const result = myArr.reduce((all, item) => { const key = item >= 0 ? 'Positive' : 'Negative'; all[key].push(item); return all; }, {Positive: [], Negative: []}); console.log(result); 

If you need to do it in JavaScript, you can do so

 let myArr = [0,-1,2,-3,4,-5,6]; let obj = {Positive: myArr.filter(e => e < 0), Negative: myArr.filter(e => e >= 0)}; console.log(obj); 

As far as I see your array definition, you are using JavaScript - don't forget to add the tag javascript .

You need the following output:

var obj = {positive: new Array(), negative: new Array()};

Iterate once through all the elements and add them to the correct array:

 var myArr = [0,-1,2,-3,4,-5,6]; var obj = {positive: new Array(), negative: new Array()}; myArr.forEach(i => { if (i>=0) { obj.positive.push(i) } else { obj.negative.push(i); } }); console.log(JSON.stringify(obj)); 

The result obj will have the following arrays:

negative : (3) [-1, -3, -5]
positive : (4) [0, 2, 4, 6]

Printed out with JSON.stringify(obj) will result in:

{"positive":[0,2,4,6],"negative":[-1,-3,-5]}

You can be explicit, and is totally find

const numbers = [0, -1, 2, -3, 4, -5, 6];
const positives = numbers.filter(number => number >= 0);
const negatives = numbers.filter(number => number < 0)
const results = {positives: positives, negatives: negatives}

console.log(results); // {positives: [0, 2, 4 ,6], negatives: [-1, -3, -5]}

I attached an executable example

 const numbers = [0, -1 , 2, -3, 4, -5, 6]; const positives = numbers.filter(number => number >= 0); const negatives = numbers.filter(number => number < 0); const results = {positives: positives, negatives: negatives}; console.log(results); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM