How to change a range of array with one value Javascript?

I have an array like below let's say

var myArray = ["1", "", "", "2","3","","","8"];

And I want to fill each " " value with previous not null value

According to that expectation should be like below

var myArray = ["1", "2", "2", "2","3","8","8","8"];

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }
    
console.log(myArray)

Upvotes: 1

Views: 1601

Answers (4)

Zevan
Zevan

Reputation: 10235

It's interesting how many different ways this can be done. Just another slightly ugly way to do the same thing:

const fill = (arr, lastVal) => (
  arr.reverse()
  .map(el => el.length > 0 ? lastVal = el : lastVal)
  .reverse()
);

console.log(fill(["1", "", "", "2","3","","","8"]));

Upvotes: 0

Rahul Pillai
Rahul Pillai

Reputation: 187

You can make use of a stack array to stack indices of null items and then unstack them whenever you encounter a non null item in myArray. (stack is not a reserved keyword so you can call it anything) :

var stack = []
for(var i = 0; i < myArray.length; i++){
   if(myArray[i] === "")
    stack.push(i);
   else if(stack.length !== 0){
       for(var j = stack.length - 1 ; j > =0; j--){
         myArray[stack[j]] = myArray[i];
         stack.splice(j,1);
       }
   }
}

Upvotes: 0

Ilijanovic
Ilijanovic

Reputation: 14914

I have done it like this. I loop over and awlays check the next element if its falsy and not the last element.

var myArray = ["1", "", "", "2","3","","","8"];

function fillArr(arr){
   for(let i = arr.length - 1; i >= 0; i--){
      if(!arr[i - 1] && i != arr.length){
         arr[i - 1] = arr[i];
      }
   }
   return arr;
}

let result = fillArr(myArray);

console.log(result);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386644

You could map the new values and find the missing following value.

var array = ["1", "", "", "2", "3", "", "", "8"],
    result = array.map((v, i, a) => v || a.find((w, j) => j > i && w));

console.log(result);

A solution with the same array, by looping from the end and storing the last value.

var array = ["1", "", "", "2", "3", "", "", "8"],
    i = array.length,
    value;

while (i--) {
    if (array[i]) value = array[i];
    else array[i] = value;
}

console.log(array);

Upvotes: 5

Related Questions