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" ] ]
10
  • 2
    I can't understand what's your goal. Could you provide an expected result? Commented Nov 24, 2018 at 11:42
  • Should it be [ ["title", "t1", null, "t3" ] ]? Commented Nov 24, 2018 at 11:44
  • @Commercial Suicide, thank you. Expected result [ [ "title", "t1", null, "t3" ] ] Commented Nov 24, 2018 at 11:45
  • is null a valid value? why a nested array structure? it makes the problem more complicated than it should be. Commented Nov 24, 2018 at 11:53
  • @Nina Scholz, no "null" is not a valid value. Don't assign "null" values. Commented Nov 24, 2018 at 11:58

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Just small addition: if you want to skip null, undefined and an empty string as well, you can use if (!v).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.