1

I have an array of number like this

   number = [4, -1, 6, -2, 3, 5, -7, 7]

Is there any way to split it when meets negative value?

So, it will be like this

array = [[4], [-1], [6], [-2], [3,5], [-7], [7]]

I think it can be done using regex, but I still not found it

Thanks

2
  • 1
    No, certainly not using a regex. Just loop over the array and append the element to a the last array or create a new one depending on the value. Commented Apr 7, 2021 at 10:44
  • @luk2302 Oh nice, I will try it first Commented Apr 7, 2021 at 10:47

2 Answers 2

2
  1. First create a few temporary arrays to hold the value(s).

  2. Loop through your main array.

  3. Then check if the number is greater than zero.

    Add the positive number to the newly created temporary array.

    Also, check for the last element and push it into the output array as required.

  4. In the else part check for the element less then zero

    Then first, push the temporary array for positive number into in output array.

    After that push the negative number temporary array for negative numbers.

    Push that temporary array for negative numbers into the output array.

    Now, reset the temporary array for both positive and negative numbers.

let number = [4, -1, 6, -2, 3, 5, -7, 7];

let array = [];
let tempArr = [];
let tempArrForNeg = [];
let numberLength = number.length;

for(let i = 0; i < numberLength; i++){
   
   if(number[i] > 0){
     tempArr.push(number[i]);
     if(i === (numberLength - 1))
       array.push(tempArr);
   }
   else{
    array.push(tempArr);
    tempArrForNeg.push(number[i]);
    
    array.push(tempArrForNeg);
    tempArr = [];
    tempArrForNeg = [];
   }
}

console.log(array);

//[[4], [-1], [6], [-2], [3,5], [-7], [7]]

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

Comments

1

Try this:

var number= [1,-2,5,6,2,-2,-3,-4,5];
console.log(splitByPositivity(number));

function splitByPositivity(numArr) {
  var newArr = []
  var tempArr = [numArr[0]];
  for (var i=1;i<numArr.length;i++){
    if (numArr[i]>0&&tempArr[tempArr.length-1]>0||numArr[i]<0&&tempArr[tempArr.length-1]<0)
       tempArr.push(numArr[i])
    else{
       newArr.push(tempArr)
       tempArr = [numArr[i]];
}
  }
newArr.push(tempArr);
return newArr;
}

Pay attention you need to handle 0 value. It is not nagitive and not positive

Comments

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.