首页 > 解决方案 > 在Javascript中按索引删除组合二维数组的值

问题描述

这里有一个 js 新手问题。我需要删除一个组合的二维数组,该数组没有按索引配对或连接的值。抱歉,我不知道正确的条款。仅以我为例:

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

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

所以,我需要"Address: " "Position: " "Birthday: "从数组中删除,剩下的是:

["First Name: John", "Last Name: Doe", "Email: john@doe.com", ""Age: 34"]

意思是,从另一个数组中删除那些不配对的。希望这是有道理的,并感谢您的帮助!

标签: javascriptarraysindexof

解决方案


您可以使用该函数Array.prototype.reduce并对空白空间(这是虚假的)应用强制以跳过这些值。

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


推荐阅读