Skip to content Skip to sidebar Skip to footer

How To Do Reduce, Filtration And Nested Array Work Javascript

How to filter out from nested array is there any way to fix it with this response please guide user is coming at object it must contain _id for this I used JSON.Stringify() which

Solution 1:

You do not need JSON.stringify() to process your data structures, you can use Optional chaining (?.) here. However, you can use JSON.stringify() for the full output:

const merged = [
  [
    {
      _id: "6136096f4255d84bcb4a7144",
      user_id: "5fbfa729fc46a415ce5503a6",
      device_platform: 'ios',
    },
    { user: { _id : "5fbfa729fc46a415ce5503a6", name : "xys" } }
  ],
  [
    {
      _id: "613609414255d84bcb4a7122",
      user_id: "5fbf6f91aff7f3320a906547",
      device_platform: 'ios',
    },
    { user: { _id : "5fbfa729fc46a415ce5503a6", name : "xys" } }
  ],
  [
    {
      _id: "613709f49223350dfdaec618",
      user_id: "5fbfa748fc46a415ce5505f1",
      device_platform: 'ios',
    },
    {
      _id: "613609184255d84bcb4a710a",
      user_id: "5fbfa748fc46a415ce5505f1",
      device_platform: 'ios',
    },
    { user: { _id : "5fbfa748fc46a415ce5503a8", name : "xys" } }
  ]
];

const user_id = ["5fbfa748fc46a415ce5503a8"];

const { matching, nonMatching } = merged.reduce(
    (acc, userRecord) => {
      if (userRecord.some(object => user_id.includes(object?.user?._id))) {
        acc.matching.push(userRecord);
      } else {
        acc.nonMatching.push(userRecord);
      }
      return acc;
    },
    { matching: [], nonMatching: [] }
);

console.log(JSON.stringify(matching, null, '  '));
console.log(JSON.stringify(nonMatching, null, '  '));

Post a Comment for "How To Do Reduce, Filtration And Nested Array Work Javascript"