-2

I am trying to separate positive and negative numbers in an array using Javascript. But the code Iam trying to use is not working. Jere is the code I was trying to use which I got from Separate negative and positive numbers in array with javascript

var t = [-1,-2,-3,5,6,1]
var positiveArr = [];
var negativeArr = [];
t.forEach(function(item){
if(item<0){
negativeArr.push(item);
}
else{
positiveArr.push(item)
})
console.log(positiveArr) // should output [5, 6, 1]
console.log(negativeArr) // should output [-1, -2, -3]
Peter G.
  • 14,786
  • 7
  • 57
  • 75
felix
  • 13
  • 2
  • 6
  • 2
    Just add `}` after `positiveArr.push(item)` – BotanMan Dec 15 '17 at 14:12
  • *"This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers."* – T.J. Crowder Dec 15 '17 at 14:14
  • Better use `for (const item of t) { … }` for the loop so that you don't get confused by the closing `})` of `forEach` – Bergi Dec 15 '17 at 14:15
  • Thanks Mr T.J. Crowder , it worked ....I didnt know it was a typo , thanks anyway – felix Dec 15 '17 at 14:17
  • Bergi Thanks I will try that too – felix Dec 15 '17 at 14:22
  • @felix: Provided your target environment supports `for-of`, which is relatively new. (Or you're transpiling.) Regarding the `}`: If you indent and format your code in a consistent, readable fashion, this sort of thing will be really obvious and so hard to accidentally leave out, and easy to fix when you do. – T.J. Crowder Dec 15 '17 at 14:23

2 Answers2

1

Your missing a closing bracket } in your conditional:

var t = [-1, -2, -3, 5, 6, 1];

var positiveArr = [];
var negativeArr = [];

t.forEach(function(item) {
  if (item < 0) {
    negativeArr.push(item);
  } else {
    positiveArr.push(item)
  }
});

console.log(positiveArr) // should output [5, 6, 1]
console.log(negativeArr)
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
0
var t = [-1,-2,-3,5,6,1];

var positiveArr = t.filter((elem) => elem > 0);
var negativeArr = t.filter((elem) => elem < 0);
devstructor
  • 1,306
  • 10
  • 12
  • 2
    And if `elem` is 0? :-) – T.J. Crowder Dec 15 '17 at 14:14
  • 0 is not neither positive nor negative. Just a zero ;-) – devstructor Dec 15 '17 at 14:17
  • no problem. Please remeber to mark your question as answered – devstructor Dec 15 '17 at 14:26
  • okay thank you let me do that now , thank you so much again you are so helpful – felix Dec 15 '17 at 14:31
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Donald Duck Dec 15 '17 at 15:35