Remove value of a combined two dimensional array by index in Javascript

277 views Asked by At

A js newbie question here. I need to remove of a value a combined two dimensional array that does not have a paired or concatenated value by index. Sorry, I don't know the right terms for this. Just for my example:

arr = [
    ["First Name", "Last Name", "Email", "Address", "Position", "Age", "Birthday"],
    ["John", "Doe", "[email protected]", "", "", "34", ""]
];
res = arr.reduce((x, y) => x.map((v, i) => v + ': '+ y[i]));

console.log(res); //["First Name: John", "Last Name: Doe", "Email: [email protected]", "Address: ", "Position: ", "Age: 34", "Birthday: "] 

So, I need to have the "Address: " "Position: " "Birthday: " removed from the array and what stays is :

["First Name: John", "Last Name: Doe", "Email: [email protected]", ""Age: 34"]

meaning, remove those don't pair from the other array. Hope this makes sense and thanks for your help!

3

There are 3 answers

0
Ele On BEST ANSWER

You can use the function Array.prototype.reduce and apply coercion over the empty space (which is falsy) to skip those values.

const arr = [    ["First Name", "Last Name", "Email", "Address", "Position", "Age", "Birthday"],   ["John", "Doe", "[email protected]", "", "", "34", ""]],
      [properties, values] = arr,
      result = values.reduce((a, v, i) => Boolean(v) ? a.concat([properties[i], ": ", v].join("")) : a, []);
      
console.log(result);

0
dipser On

arr = [
    ["First Name", "Last Name", "Email", "Address", "Position", "Age", "Birthday"],
    ["John", "Doe", "[email protected]", "", "", "34", ""]
];
res = arr.reduce(function(x, y){
  return x.map(function(v, i) {
    if (!['Birthday', 'Age'].includes(v)) return v + ': '+ y[i]; 
  }).filter(x => x !== undefined);
});

console.log(res);

1
Pasha K On

something like this

arr = [
    ["First Name", "Last Name", "Email", "Address", "Position", "Age", "Birthday"],
    ["John", "Doe", "[email protected]", "", "", "34", ""]
];
res = arr
   .reduce((x, y) => x
   .map((v, i) => { if (y[i]) return v + ': '+ y[i]}))
   .filter(Boolean);

console.log(res);