Search code examples
javascriptarraysmergestore

Reactjs trying to merge arrays


Let's say I have two array's

let array1 = ["H","E","", "","O","","","R","L","D"];
let array2 = ["","","L","L","","W","O","","",""];

I want to merge them such that they would then contain:

array3 = ["H","E","L", "L","O","W","O","R","L","D"];

How would I achieve this? To be more clear I have a target array which is array3 an empty array and then I'm generating random characters and if they match array3 adding them to the blank array in the specific position with react state. It is just not storing the position and character each time but just changing it. SO my idea is to set the state such that I merge the current state with the new characters that are found.

TLDR:- Brute forcing Hello World meme.


Solution

  • You can use Array.prototype.map() to create a new array array3 out of iterating over array1 and get the l (letters) and if any l evaluates to falsey then get the letter at the same i (index) in the array2.

    Note that instead of declaring your arrays with let you should always use const because it makes code easier to read within its scope, and const variable always refers to the same object.

    Code example:

    const array1 = ["H","E","", "","O","","","R","L","D"];
    const array2 = ["","","L","L","","W","O","","",""];
    
    const array3 = array1.map((l, i) => l || array2[i]);
    
    console.log(array3);