javascriptinterleave

Selectively interleave two arrays


I would like to interleave two arrays, BUT only return pairs when a certain condition is met. As an example:

first_array = [1, 2, 3, 4, 5, 6, 7, 8];
second_array = [, , , , 1, , 0, 1];

I need to return ONLY pairs where array-2 is non-null, in other words, the output I need is:

interleaved = [5, 1, 7, 0, 8, 1];

I have an interleave function that works:

function send_values() {
    let interleaved = [];
    for (let i = 0; i < first_array.length; i++) {
       interleaved.push(first_array[i], second_array[i]);
        }
    }

...but the output is, obviously: interleaved = [1, , 2, , 3, , 4, , 5, 1, 6, , 7, 0, 8, 1];

...which is not what I need. Suggestions?


Solution

  • You could iterate the sparse array and take only the values with the values at the same index from array one.

    var array1 = [1, 2, 3, 4, 5, 6, 7, 8],
        array2 = [, , , , 1, , 0, 1],
        result = array2.reduce((r, v, i) => r.concat(array1[i], v), []);
        
    console.log(result);