【问题标题】:Trying to compare an array with another array nested in an object尝试将数组与嵌套在对象中的另一个数组进行比较
【发布时间】:2021-05-29 07:53:58
【问题描述】:

我在这个问题上已经卡住了一段时间。如果有人对我如何解决这个问题有任何指导。

此函数返回访问给定用户愿望清单中任何公园的所有用户名。

getUsersForUserWishlist(users, "karah.branch3"); //> ["dwayne.m55"]
getUsersForUserWishlist(users, "dwayne.m55"); //> []

const parks = [{
    id: 1,
    name: "Acadia",
    areaInSquareKm: 198.6,
    location: {
      state: "Maine"
    },
  },
  {
    id: 2,
    name: "Canyonlands",
    areaInSquareKm: 1366.2,
    location: {
      state: "Utah"
    },
  },
  {
    id: 3,
    name: "Crater Lake",
    areaInSquareKm: 741.5,
    location: {
      state: "Oregon"
    },
  },
  {
    id: 4,
    name: "Lake Clark",
    areaInSquareKm: 10602,
    location: {
      state: "Alaska"
    },
  },
  {
    id: 5,
    name: "Kenai Fjords",
    areaInSquareKm: 2710,
    location: {
      state: "Alaska"
    },
  },
  {
    id: 6,
    name: "Zion",
    areaInSquareKm: 595.9,
    location: {
      state: "Utah"
    },
  },
];

const users = {
  "karah.branch3": {
    visited: [1],
    wishlist: [4, 6],
  },
  "dwayne.m55": {
    visited: [2, 5, 1],
    wishlist: [],
  },
  thiagostrong1: {
    visited: [5],
    wishlist: [6, 3, 2],
  },
  "don.kim1990": {
    visited: [2, 6],
    wishlist: [1],
  },
};

function getUsersVisitedForUserWishlist(users, username) {}

【问题讨论】:

    标签: javascript arrays function object oop


    【解决方案1】:

    这解决了你的问题

     function getUsersForUserWishlist(users1, userName) {
            //Retreive the user wishlist
            var wishlistInd = users1[arguments[1]]["wishlist"];
            var arrayRes = [];
            //loop throght users array
            for (const [key, value] of Object.entries(users1)) {
               var filteredArray = [];
              if (  `${key}` !== userName ) {
               var filteredArray = value['visited'].filter(value => 
                wishlistInd.includes(value));
                if  (filteredArray.length != 0 ) {
                  arrayRes.push( `${key}`);
                }
              }
            }
            return arrayRes;
            }
    

    【讨论】:

      【解决方案2】:

      如果我正确理解您的函数必须返回(如下例所示)而不是您的示例中提到的:

      getUsersForUserWishlist(users, "karah.branch3"); //> ["don.kim1990"]
      getUsersForUserWishlist(users, "dwayne.m55"); //> []
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 2019-04-06
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-26
        相关资源
        最近更新 更多