settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Negative and Positive Numbers - JavaScript task

+3 votes

Write a JavaScript function that processes the elements in an array one by one and produces a new array.

Prepend each negative element at the front of the result and append each positive (or 0) element at the end of the result.

The input comes as array of number elements.

Examples:

Input:
[7, -2, 8, 9]

Output:
-2
7
8
9


Input:
[3, -2, 0, -1]

Output:
-1
-2
3
0

The output is printed on the console, each element on a new line.

asked in JavaScript category by user hues

1 Answer

+2 votes

Use .unshift and .push methods:

function negativePositive(arrNums) {
    let arrNew = [];
    for (let i of arrNums) {
        if (i < 0) {
            arrNew.unshift(i);//.unshift adds to the left - most first position
        }
        if (i > 0) {
            arrNew.push(i);//.push adds to the most right - end position
        }
        if (i == 0) {
            arrNew.push(i);
        }
    }
    console.log(arrNew.join("\n"));//prints the result on empty line
}

negativePositive([3, -2, 0, -1]);

 

answered by user icabe
...