Longway_togo
Longway_togo

Reputation: 87

Remove negative value from an array and arrange positive value in ascending order

Get totally lost. How to write in a correct way?

var i = [1, -2, 3, -4, 5, 7, -6];
for (i = 0, i < 7, i++) {
    if (i[0] >= 0 && i[0] <= i[1]) {
        continue;
    } else {
        i[0] = i[1];
        break;
    } else {
        if (i[i]) < 0) i.splice(i, 1);
    }
}

document.write("array[i]");

Upvotes: 0

Views: 1710

Answers (3)

Guffa
Guffa

Reputation: 700192

If you first sort the array, all the negative items are at the beginning of the array, so you can just loop through them to find the first one to keep, and take the part of the array from that point:

i.sort(function(x, y) { return x - y; });
var index = 0;
while (index < i.length && i[index] < 0) index++;
i = i.slice(index);

document.write(i);

Upvotes: 0

Abdulrahman Awwad
Abdulrahman Awwad

Reputation: 122

var myArray = [7, -2, 3, -4, 5, 1, -6];
for (i=0;i<myArray.length;i++) 
{
 if (myArray[i]<0)
  myArray.splice(i, 1);
}
myArray.sort();

Upvotes: 0

MikeHelland
MikeHelland

Reputation: 1159

i.filter( function (el) {return el >= 0;});
i.sort( function (a, b) {return a - b;});

Upvotes: 2

Related Questions