【问题标题】:Compare two arrays and filter them javascript比较两个数组并过滤它们 javascript
【发布时间】:2020-07-03 15:34:26
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript arrays reactjs loops array.prototype.map


    【解决方案1】:

    给你一个解决方案

    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 将返回您可以呈现的过滤按钮。

    【讨论】:

      【解决方案2】:

      您可以遍历buttonGroups 并获得结果:

      buttonGroups.map(button => {return buttons[button]})
      

      【讨论】:

        【解决方案3】:

        使用filter 方法。

        const filterBtn = buttons.filter((btn,index) => buttonGroups.includes(index));
        

        【讨论】:

        • 那将是错误的顺序。 buttonGroups 还指示按钮的顺序,请尝试使用 buttonGroups 为 [3,1] 的代码。解决方案要简单得多,是:buttonGroups.map((i) => buttons[i])
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        • 2015-08-04
        • 2020-03-16
        • 2016-10-24
        • 1970-01-01
        相关资源
        最近更新 更多