Home > Mobile >  Javascript Array. Add first array to the first position that has a zero
Javascript Array. Add first array to the first position that has a zero

Time:02-01

How would I do the following as mentioned in the title. I have looked online and I can push, slice etc to add the item but I want the first value to go to the first available position in the array that has a zero value;

For example:

var arr = [4,1,2,7,10,0,0,0];
arr = arr.concat(arr.shift())

document.write(arr);

I want the output to be, 0, 1, 2, 4, 7, 10, 0, 0, 0, 0;

So the first number in the array is sorted correctly, and replaced correctly and the last array is removed as the length should always remain the same - in this case eight;

Thanks.

CodePudding user response:

You can find the first position in the array with a zero value and splice the first value there. Just like this:

var arr = [4, 1, 2, 7, 10, 0, 0, 0];
var zeroIndex = arr.indexOf(0);
arr.splice(zeroIndex, 0, arr.shift());

document.write(arr);

CodePudding user response:

Your question is somewhat cryptic but I'm sure the more you program and read on stackoverflow you get more decent in explaining what you want to achieve.

Maybe your problem can be broken down in a simple reduce function that sorts the array one single time.

Aka add any number to our new array. If you find a 0 sort it - if you have not already.

const arr = [4,1,2,7,10,0,0,0];

const specialSortedArr = arr.reduce((acc, curr) => {
      acc.push(curr);   
      // if there is not already a 0 in pole position lets sort the array we have!
      if (curr === 0 && acc[0] !== 0) {
        acc = acc.sort((a, b) => a - b);
       }
  return acc;
}, []);

console.log(specialSortedArr)

  • Related