Hari
Hari

Reputation: 1

Get non unique records from json array node js

I have one requirement that will get json array object it looks like below(input) json i need to get dupliacte records & unquie records and load it into respective list. condition to check wether array has duplicates or not :: id

let uniqueList = [];
let dupList = [];

Array.prototype.contains = function (item) {
    let filtered_item = this.filter((i) => {
        return i.id === item.id
    });
    return !!filtered_item.length;
}

function contains(list, item) {
    let filtered_item = list.filter((i) => {
        return i.id === item.id
    });
    return !!filtered_item.length;
}

function pushToUniqueList(item) {
    uniqueList.push(item);
}

function pushToDuplicateList(item) {
    dupList.push(item);
}

for (let i = 0; i < objList.length; i++) {
    if (uniqueList.contains(objList[i])) {
        pushToDuplicateList(objList[i]);
    } else {
        pushToUniqueList(objList[i]);
    }
}
Input : [{"obj":{"id":"1234","table":"123"}},{"obj":{"id":"1234","table":"123"}},{"obj":{"id":"12344","table":"123"}}]
output : uniqueList =[{ "obj":{ "id":"12344", "table":"123" }]
dupList =[{"obj":{"id":"1234","table":"123"}},{"obj":{"id":"1234","table":"123"}}]

I have tried with above code but its not working Please help!Thanks in advance!

Upvotes: 0

Views: 49

Answers (1)

yondu_udanta
yondu_udanta

Reputation: 807

You can try the below, this code runs in linear time

const data = [
      { obj: { id: "1234", table: "123" } },
      { obj: { id: "1234", table: "123" } },
      { obj: { id: "12344", table: "123" } },
    ];
    
    const map = new Map();
    
    for (const entry of data) {
      if (map.has(entry.obj.id)) {
        map.get(entry.obj.id).push(entry);
      } else {
        map.set(entry.obj.id, [entry]);
      }
    }
    
    const uniques = [];
    const duplicates = [];
    
    for (const [id, values] of map.entries()) {
      if (values.length > 1) {
        duplicates.push(...values);
      } else {
        uniques.push(...values);
      }
    }
    
    console.log(`duplicates: ${JSON.stringify(duplicates)}`);
    console.log(`unique: ${JSON.stringify(uniques)}`);

Output

[
  { obj: { id: '1234', table: '123' } },
  { obj: { id: '1234', table: '123' } }
] [ { obj: { id: '12344', table: '123' } } ]

Upvotes: 2

Related Questions