-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]
6
  • 2
    Just add } after positiveArr.push(item) Commented Dec 15, 2017 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." Commented Dec 15, 2017 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 Commented Dec 15, 2017 at 14:15
  • Thanks Mr T.J. Crowder , it worked ....I didnt know it was a typo , thanks anyway Commented Dec 15, 2017 at 14:17
  • Bergi Thanks I will try that too Commented Dec 15, 2017 at 14:22

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Typo/non-repro/not-useful-to-others-in-future questions don't need answers, just close votes and comments.
0
var t = [-1,-2,-3,5,6,1];

var positiveArr = t.filter((elem) => elem > 0);
var negativeArr = t.filter((elem) => elem < 0);

5 Comments

And if elem is 0? :-)
0 is not neither positive nor negative. Just a zero ;-)
no problem. Please remeber to mark your question as answered
okay thank you let me do that now , thank you so much again you are so helpful
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.