1

I have a payload that is an array of objects. I want to remove duplicate objects with the same id however if the returnComment is 1, that should be kept over the one being 2. Basically 1 has higher priority over 2 in deciding which object to keep. How would one do it based on this condition?

Payload:

[
    {
      "id": "1676431",
      "returnComment": 2
    },
    {
      "id": "1676431",
      "returnComment": 1
    },
    {
      "id": "1676431",
      "returnComment": 2
    },
    {
      "id": "3566367",
      "returnComment": 2
    },
    {
      "id": "7676559",
      "returnComment": 1
    },
    {
      "id": "7676559",
      "returnComment": 1
    }
]

Expected Output:

[
    {
      "id": "1676431",
      "returnComment": 1
    },
    {
      "id": "3566367",
      "returnComment": 2
    },
    {
      "id": "7676559",
      "returnComment": 1
    },
]

Current Code:

%dw 2.0
output application/json

---

arr distinctBy $.requestId
aled
  • 21,330
  • 3
  • 27
  • 34
Andre S
  • 21
  • 6
  • What is `arr` in your script? – aled Apr 18 '23 at 11:29
  • arr is just the payload – Andre S Apr 18 '23 at 17:42
  • Then just use payload. It should be easy for people to reproduce what you are trying to do. Using a non existent variable means that the script as is doesn't work. People may waste effort into that instead of your actual issue. – aled Apr 18 '23 at 18:16

1 Answers1

0

You can first orderBy returnComment so all 1's will come first followed by 2's then if you order by id 1's will be picked as first priority over 2 and final ordering is to sort based on id's.

DataWeave:

%dw 2.0
output application/json
---
(((payload orderBy $.returnComment) distinctBy $.id) orderBy $.id)

Output:

[
  {
    "id": "1676431",
    "returnComment": 1
  },
  {
    "id": "3566367",
    "returnComment": 2
  },
  {
    "id": "7676559",
    "returnComment": 1
  }
]
aled
  • 21,330
  • 3
  • 27
  • 34
Karthik
  • 2,181
  • 4
  • 10
  • 28