0

When initial arrays contain undefined elements this code works great:

var x = [];
x[0] = ["title","t1"];
var y = []; y[0] = []; y[0][3]="t3";

console.log(x);
console.log(y);

y.forEach((subarr, i) => {
  Object.assign(x[i], subarr);
});

console.log(x);

What should I change to make this code works for initial arrays which may contain null elements and undefined elements:

var x = [];
x[0] = ["title","t1"];
var y = []; y[0] = [null,undefined,null,"t3"];

console.log(x);
console.log(y);

y.forEach((subarr, i) => {
  Object.assign(x[i], subarr);
});

console.log(x);

I'd like to get the same result as in the first example but for initial arrays which may contain null and undefined elements. Expected result:

[ [ "title", "t1", null, "t3" ] ]
  • 2
    I can't understand what's your goal. Could you provide an expected result? – P.S. Nov 24 '18 at 11:42
  • Should it be `[ ["title", "t1", null, "t3" ] ]`? – P.S. Nov 24 '18 at 11:44
  • @Commercial Suicide, thank you. Expected result [ [ "title", "t1", null, "t3" ] ] –  Nov 24 '18 at 11:45
  • is `null` a valid value? why a nested array structure? it makes the problem more complicated than it should be. – Nina Scholz Nov 24 '18 at 11:53
  • @Nina Scholz, no "null" is not a valid value. Don't assign "null" values. –  Nov 24 '18 at 11:58
  • why does the wanted result have a `null` value? – Nina Scholz Nov 24 '18 at 12:00
  • @Nina Scholz, the wanted result should not have a "null" value. I'd like to assign only the values which are not "null' and not "undefined". The expected result of the second code is in the topic: [ [ "title", "t1", null, "t3" ] ] –  Nov 24 '18 at 12:03
  • but expected result shows a null value. what to do? – Nina Scholz Nov 24 '18 at 12:04
  • In your first example, your array doesn't contain `undefined` values. It rather [does not have the respective properties](https://stackoverflow.com/questions/1510778/are-javascript-arrays-sparse), so there's nothing that could get copied. – Bergi Nov 24 '18 at 12:05
  • @Nina Scholz, I'm not sure that I understood your question correctly. The expected result of the second code from the topic is [ ["title", "t1", null, "t3" ] ]. –  Nov 24 '18 at 12:08

1 Answers1

1

You could skip undefined and null values.

var x = [["title", "t1"]],
    y = [[null, undefined, null, "t3"]];

y.forEach((subarr, i) => subarr.forEach((v, j) => {
    if (v === undefined || v === null) return;
    x[i] = x[i] || [];
    x[i][j] = v;
}));

console.log(x);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Just small addition: if you want to skip `null`, `undefined` and an empty string as well, you can use `if (!v)`. – P.S. Nov 24 '18 at 12:07