【问题标题】:Check whether there is at least one occurrence of all the elements in the main array inside the sub array identified by an identifier javascript检查由标识符javascript标识的子数组内的主数组中的所有元素是否至少出现一次
【发布时间】:2019-11-22 04:56:33
【问题描述】:
let mainList = [ 2, 3, 5];
let subList = [
        {
            id: 23,
            name: "ABC",
            parent_id: 2
        },
        {
            id: 25,
            name: "DEF",
            parent_id: 2
        },
        {
            id: 26,
            name: "GHI",
            parent_id: 3
        }
    ];

我需要检查在由parent_id 标识的子列表内的主列表中的所有元素是否至少出现一次。

我目前是如何实现这一目标的

 let matchFound = true;
   mainList.forEach(mainItem => {
        matchFound =
            matchFound &&
            Boolean(
                subList.find(
                    sub_item =>
                        mainItem === sub_item.parent_id
                )
            );
    });

想知道是否有更清洁的方法来做到这一点。

【问题讨论】:

    标签: javascript arrays loops object foreach


    【解决方案1】:

    如果subList 不是很大,我会使用everysome

    const mainList = [2, 3, 5];
    const subList = [{ id: 23, name: 'ABC', parent_id: 2 }, { id: 25, name: 'DEF', parent_id: 2 }, { id: 26, name: 'GHI', parent_id: 3 }];
    const matchFound = mainList.every(
      mainItem => subList.some(
        subItem => mainItem === subItem.parent_id
      )
    );
    
    console.log(matchFound);

    【讨论】:

      【解决方案2】:

      我会将subList 变成ids 的Set,然后检查mainList 中的每个项目是否都包含在集合中:

      let mainList = [2, 3, 5];
      let subList = [{
          id: 23,
          name: "ABC",
          parent_id: 2
        },
        {
          id: 25,
          name: "DEF",
          parent_id: 2
        },
        {
          id: 26,
          name: "GHI",
          parent_id: 3
        }
      ];
      const parentIdSet = new Set(
        subList.map(({ parent_id }) => parent_id)
      );
      const hasAll = mainList.every(item => parentIdSet.has(item));
      console.log(hasAll);

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 2015-06-08
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        相关资源
        最近更新 更多