Home > Net >  How to only rotate the positive numbers
How to only rotate the positive numbers

Time:10-31

I would like to rotate the array. it works my code. But I would like to rotate only the positive numbers.

how to get it?

here is my try:

const ar = [1,2, -8, 3,4,5,-3,-44];

for(let i = 0; i< 3; i  ){
  ar.unshift(ar.pop());
}

console.log(ar);

I am getting a result as : [5, -3, -44, 1, 2, -8, 3, 4];

But looking for the result as : [3,4,-8, 5, 1, 2, -3, -44,] so only the positive numbers can be rotated. but still if there is a negative number, that should not be touched.

any help please?

CodePudding user response:

One approach would be to take only the positives, then slice them and recombine to "rotate", and then map back onto the original array by replacing positive numbers with elements from the rotated array.

const arr = [1, 2, -8, 3, 4, 5, -3, -44];
const positives = arr.filter(num => num >= 0);
// Rotate positives by the desired amount
const rotated = positives.slice(2).concat(positives.slice(0, 2));
const output = arr.map(num => num >= 0 ? rotated.shift() : num);
console.log(output);

  • Related