简体   繁体   English

比较两个数组并过滤它们javascript

[英]Compare two arrays and filter them javascript

Basically i have two arrays which i am using it for the configuration of buttons.基本上我有两个数组,我用它来配置按钮。

First array which defines how many buttons should be present and in order.第一个数组定义应该按顺序显示多少个按钮。

buttonGroups: [ 0, 2 ]

Another array of objects which says about the actual buttons.另一个关于实际按钮的对象数组。

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

The buttonGroups is the configuration array. buttonGroups是配置数组。 If it has only [0, 1] then first two buttons will exist.如果它只有[0, 1]则前两个按钮将存在。 If buttonGroups has only [0, 3] we should have first and third button exists in buttons array.如果buttonGroups只有[0, 3]我们应该有第一个和第三个按钮存在于buttons数组中。

This is what i have tried这是我尝试过的

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

This is giving the first index button array.这是给出第一个索引按钮数组。 How to get the matched array buttons?如何获得匹配的数组按钮?

Here you go with a solution给你一个解决方案

 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 will return the filtered buttons which you can render. filteredButtons按钮将返回您可以渲染的过滤按钮。

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

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

使用filter方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM