1

How do I fill elements of an array on another array with respecting the size Example

Arra1 = ["1","2","3","4","5"]
Arra2 = ["R","B"]
result = ["R","B","R","B","R"]

How can I achieve that

1
  • please clarify this: "with respecting the size" Commented Aug 13, 2022 at 9:45

2 Answers 2

1

You could do Array.map() with modulo %:

let Arra1 = ["1","2","3","4","5"]
let Arra2 = ["R","B"]
console.log(Arra1.map((num, ind)=>Arra2[ind%Arra2.length]))
//["R","B","R","B","R"]
Sign up to request clarification or add additional context in comments.

Comments

1

You can write this :

r = []
let j = 0
for (let i=0; i<Arra1.length; i++)
{
    if (j>= Arra2.length)
        j = 0
    r.push(Arra2[j])
    j++
}

Hope it helps.

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.