1

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?

Paul Clift
  • 169
  • 8
  • 1
    Note that `array-1` is an invalid variable name, you'll get a `SyntaxError`. Sparse arrays are generally a pain to work with and should probably be avoided when possible – CertainPerformance Dec 06 '18 at 10:08
  • Hi! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Nothing in your code tries to fulfill the condition you describe. Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Dec 06 '18 at 10:10
  • @CertainPerformance Yes, I know. This was just to illustrate what I need. I have edited the var names. – Paul Clift Dec 06 '18 at 10:12

2 Answers2

2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Of course, that won't work if there are physical `null`s in the second array instead of elisions. – georg Dec 06 '18 at 10:17
  • Both very elegant solutions! Neither array will contain a physical 'null', but rather, just an empty value. – Paul Clift Dec 06 '18 at 11:13
1

Here's a generic functional solution:

pairs = (a, b) => a.map((_, i) => [a[i], b[i]])
flat = a => [].concat(...a)
valid = x => x === 0 || Boolean(x)


array_1 = [1, 2, 3, 4, 5, 6, 7, 8];
array_2 = [ ,  ,  ,  , 1,  , 0, 1];


result = flat(
    pairs(array_1, array_2)
        .filter(x => x.every(valid))
)

console.log(result)

Works both ways, that is, it doesn't matter which array contains the null values. Also, you can redefine valid if there are other things to exclude.

As a bonus, if you replace pairs with zip, you can make it work for any number of arrays.

georg
  • 211,518
  • 52
  • 313
  • 390