Home > OS >  How can I create the MissingUserIdsArray from MainArray in Javascript?
How can I create the MissingUserIdsArray from MainArray in Javascript?

Time:01-27

How can I create the MissingUserIdsArray from MainArray in JavaScript?

var MainArray = [
  [
    "10148835*1,2,3,",
    "1,2,3,4,5,"
  ],
  [
    "10148839*4,5,",
    "1,2,3,4,5,"
  ]
];

const MappedArrray = MainArray.map(arr => {
  const SplitID = arr[0].split("*"); 
  return {"AppId": SplitID[0], "AppUserIds": SplitID[1].split(","), "MeetingUserIds": arr[1].split(",")};
});
console.log(MappedArrray);
//My above code is working fine. Just need to make MissingUserIdsArray array in the format I mentioned.

const MissingUserIdsArray = MappedArrray.map(arr => arr.MeetingUserIds.filter(x => !arr.AppUserIds.includes(x)));
console.log(MissingUserIdsArray);

//Need to create MissingUserIdsArray in the following format:
/*
MissingUserIdsArray = [
    {"AppId": 10148835, "MissingUserIds": "4,5"},
    {"AppId": 10148839, "MissingUserIds": "1,2,3"},
]

*/

CodePudding user response:

There wasn't much missing in your code:

  • The trailing comma in the source data makes me choose match over split
  • Join the array you had to get the comma separated values

var MainArray = [["10148835*1,2,3,","1,2,3,4,5,"],["10148839*4,5,","1,2,3,4,5,"]];

const MappedArrray = MainArray.map(([a, b]) => {
    const [AppId, ...appUserIds] = a.match(/\d /g);
    const MissingUserIds = b.match(/\d /g).filter(id => !appUserIds.includes(id)).join();
    return {AppId, MissingUserIds};
});
console.log(MappedArrray);

CodePudding user response:

Just split up the strings into a processable format and then exclude one set of ids from the other:

const MainArray = [
  [
    "10148835*1,2,3,",
    "1,2,3,4,5,"
  ],
  [
    "10148839*4,5,",
    "1,2,3,4,5,"
  ]
];

const result = MainArray
  .map( ([s, ids]) => [...s.split('*'), ids.split(',')])
  .map(([AppId, excludes, ids]) => (excludes = excludes.split(','), {AppId, MissingUserIds: ids.filter(id => !excludes.includes(id)).join(',') }) )
console.log(result)

  • Related