skip to Main Content

I am getting below response, i wanted to remove all the duplicates object based on lineId and status.
I am trying to find all the duplicates with new status in below response.

In the below example, i wanted to remove those objects whose lineId is same but status is New.

i tried below code but unable to filter the expected result.

I appreciate any help on this.

const response = [
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "New"
    },
    {        
        "line": "Line 3",
        "lineId": "R_X002_WC03",
        "status": "New"
    },
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "Submitted"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "New"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "Submitted"
    }
];

Below is my expected Output

const ExpectedOutput = [    
    {        
        "line": "Line 3",
        "lineId": "R_X002_WC03",
        "status": "New"
    },
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "Submitted"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "Submitted"
    }
];

i tried below code

var finalarr = [];
response.forEach((item) => {
        response.filter(i => i.lineId === item.lineId).length > 1
        finalarr.push(item);
      });

2

Answers


  1. const unique = new Set();
    const finalarr = response.filter(item => {
        if (unique.has(item.lineId)) {
            return false; 
        } else {
            unique.add(item.lineId);
            return true;
        }
    });

    try this it works according to what you want

    Login or Signup to reply.
  2. One good way will be to convert this array to a new object where you keys are the key of the object and value can be the object itself. This will get rid of any duplicates

    var finalarr = {};
    response.forEach((item) => {
            if(!finalarr[i.lineId] {
                finalarr[i.lineId] = i;
            }
        
          });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search