首页 > 解决方案 > 比较两个数组并过滤它们 javascript

问题描述

基本上我有两个数组,我用它来配置按钮。

第一个数组,它定义了应按顺序显示的按钮数量。

buttonGroups: [ 0, 2 ]

另一个关于实际按钮的对象数组。

    buttons = [
    {
        buttonLabel: 'label1',
        cond1: true,
        cond2: false
    },
    {
        buttonLabel: 'label2',
        cond1: true,
        cond2: false
    },
    {
        buttonLabel: 'label3',
        cond1: false,
        cond2: true
    }
];

buttonGroups配置数组。如果它只有[0, 1]那么前两个按钮将存在。如果buttonGroups只有我们应该在数组中[0, 3]存在第一个和第三个按钮。buttons

这是我尝试过的

buttonGroups.map((payload1, index1) => {
    buttons .map((payload2, index2) => {
        if(index1 === index2){
            //Display Here only the matched index from ButtonGroups
            console.log(payload2)
        }
    })
})

这是第一个索引按钮数组。如何获得匹配的数组按钮?

标签: javascriptarraysreactjsloopsarray.prototype.map

解决方案


给你一个解决方案

var buttonGroups = [ 0, 2 ];


var buttons = [
  {
    buttonLabel: 'label1',
    cond1: true,
    cond2: false
  },
  {
    buttonLabel: 'label2',
    cond1: true,
    cond2: false
  },
  {
    buttonLabel: 'label3',
    cond1: false,
    cond2: true
  }
];

var filteredButtons = buttonGroups.map(item => {
  return buttons[item];
});

console.log(filteredButtons);

filteredButtons将返回您可以呈现的过滤按钮。


推荐阅读