简体   繁体   中英

How to compare 2 array of object and return single array outcome in Javascript?

I have 2 array of object in javascript. Both object share the common attribute called "loc". Based on the "loc" attribute, i need to return another array which will hold all "loc" attribute which is got expired. I have written all logic but i am not getting desired outcome. Source code as follow for the issue.

const data = [
  {
    depId: "AB234",
    loc: "ESP",
  },
  {
    depId: "AB234",
    loc: "CAT",
  },
  {
    depId: "AB234",
    loc: "AUS",
  },
  {
    depId: "AB234",
    loc: "JAP",
  },
  {
    depId: "AB234",
    loc: "USA",
  },
  {
    depId: "AB234",
    loc: "MAL",
  },
  {
    depId: "AB123",
    loc: "AUS",
  },
  {
    depId: "AB123",
    loc: "JAP",
  },
];

const locDates = [
  {
    loc: "ESP",
    expiryDate: "18/12/2020",
  },
  {
    loc: "CAT",
    expiryDate: "19/12/2020",
  },
  {
    loc: "AUS",
  },
  {
    loc: "JAP",
  },
  {
    loc: "USA",
    expiryDate: "30/12/2020",
  },
  {
    loc: "MAL",
    expiryDate: "30/12/2020",
  },
];

const getLocData = (loc) => {
  let data = [];
  locDates.map((item) => {
    if (item.expiryDate && item.loc === loc) {
      data.push(item);
    }
  });
  return data;
};
  const filterData = data.filter((item) => item.depId === "AB234");
  let locInfo = "";
  filterData.map((item) => {
    locInfo = getLocData(item.loc);
  });
  const currentDate = "27/12/2020";
  const infoArray = [];
  locInfo.map((item) => {
    if (
      moment(currentDate, "DD/MM/YYYY") > moment(item.expiryDate, "DD/MM/YYYY")
    ) {
      infoArray.push(item.loc);
    }
  });
  // expected outPut ["ESP", "CAT"]
  console.log("infoArray", infoArray);

From looking at your code, I see the issues with your code. I think you do not understand how the map function works, and that's why you are getting confused and cannot solve this problem. I suggest you to try using for loop and if-else statements to solve this problem. If you specifically want to use the map function, do read up some articles about it or Mozilla array.prototype.map documentation first, learn the correct use, and then try using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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