0

How to fill the missing values in the array1

array1 = [1,'',12,23,'',5]

basically, they are 3 values but only 2 values can be placed

array2 = [6,8,9]

sample output

array1 = [1,6,12,23,8,5]
array2 = [9]
3
  • 1
    Welcome to Stack Overflow! Please take the tour if you haven't already (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO and elsewhere, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example showing your attempt and say specifically where you're stuck. People will be glad to help. Commented Mar 24, 2022 at 9:34
  • Just a side note: Those aren't missing values, they're strings. I mention this because JavaScript arrays can actually have missing values because they can be sparse. You could create that array with actually missing values by doing this: const array1 = []; array1[0] = 1; array1[2] = 12; array[3] = 23; array1[5] = 5; or slightly more obscurely: const array1 = Object.assign([], {0: 1, 2: 12, 3: 23, 5: 5}); Commented Mar 24, 2022 at 9:37
  • 1
    @t-j-crowder this is noted. Next time I'll include my attempts in my questions. Thank you so much! Commented Mar 24, 2022 at 9:43

3 Answers 3

3

Start with something like this.

array1 = [1,'',12,23,'',5]
array2 = [6,8,9]
array1 = array1.map(val => val === '' ? array2.shift() : val);

Or

for (let i = 0; i < array1.length; i++) {
  if (array1[i] === '') array1[i] = array2.shift();
}

Read about https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift. Have fun!

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

Comments

0
let array1 = [1,'',12,23,'',5]
let array2 = [6,8,9]
for (var i = 0; i < array1.length; i++) {
    if(array1[i]=== ''){
        console.log(array1[i])
         array1[i] = array2.shift()
    }
}

Comments

0

let array1 = [1,'',12,23,'',5];
const array2 = [6,8,9];

array1 = array1.map((item) => {
    if (Boolean(item)) {
        return item
    } else {
        return array2.shift();
    }
});

console.log(array1);
console.log(array2);

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.