javascript查找两个嵌套数组之间的匹配变量

时间:2019-02-06 17:35:15

标签: javascript

我有两个嵌套数组。

arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
arr2 = [["image1","blue"],["image2","red"]]

所需的输出是:如果图像名称(image)匹配,我想将颜色从第二个数组返回到变量。

我尝试使用两个for循环:

var color = for (var i = 0; i < arr1.length; i++ ) {
for (var j = 0; j < arr2.length; j++ ) {
if (arr1[i][0] === arr2[j][0]) {
return arr2[j][1]
}
}

由于这是程序的较大部分,因此第一个循环在第二个循环之前执行了很多。但是,两者都按照我指定的顺序相互嵌套.....我正在尝试使用该变量为一些html元素着色,但是我的整个程序被暂停。我不确定我的方法是否正确。

3 个答案:

答案 0 :(得分:1)

感觉就像您尝试使用第二个数组作为对第一个数组的查找一样。这是通过将其转换为对象来实现的方法:

 function toLookupTable(shirtColors) {

     //keys will be image names, values will be colors
     const lookupTable = {};

     shirtColors.forEach(shirtColor => {
         //use array destructuring
         const [ image, color ] = shirtColor;
         lookupTable[image] = color;
     });
     return lookupTable;
 }

 const colorLookup = toLookupTable( [["image1","blue"],["image2","red"]] );

 console.log(colorLookup["image2"]); //outputs "red"

答案 1 :(得分:1)

使用Array#reduce和Array#findIndex

  

我想将颜色从第二个数组返回到变量。

const arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]]
const arr2 = [["image1", "blue"],["image2","red"]]

const res = arr2.reduce((a,[image,color])=>{
   if(arr1.findIndex(([n])=>n===image) > -1) a.push(color);
   return a;
}, []);

console.log(res);

答案 2 :(得分:0)

您可以使用reduce

let arr1 = [["image1","shirt", "collared",40],["image3","shirt", "buttoned",40]];
let arr2 = [["image1","blue"],["image2","red"]];

let op = arr1.reduce((out,inp,index)=>{
  if(arr2[index].includes(inp[0])){
    out.push(arr2[index][1])
  }
  return out
},[] )

console.log(op)