Home > Software design >  I need to check is there any duplicate array exist or not
I need to check is there any duplicate array exist or not

Time:07-13

var myarray = [ { "msf": "3.98", "ptc": "5.00" }, { "msf": "3.98", "ptc": "1.00" }, { "msf": "3.98", "ptc": "1.00" } ]

Expect answer is : true

CodePudding user response:

This is a hacky way. But I can sure there's a better way.

var myarray = [ { "msf": "3.98", "ptc": "5.00" }, { "msf": "3.98", "ptc": "1.00" }, { "msf": "3.98", "ptc": "1.00" } ]
const seen=[];
const dupe=[];
myarray.forEach(e=>(seen.includes(JSON.stringify(e))?dupe:seen).push(seen.includes(JSON.stringify(e))?e:JSON.stringify(e)))
console.log(dupe);

CodePudding user response:

Using Sets:

// combine the properties so Set can be used
let uniqueArrayString = [
    ...new Set(myArray.map((item) => item.msf   '-'   item.ptc)),
];
// separate the msf and ptc
let uniqueArrayObject = uniqueArrayString.map((item) => {
    return {
        msf: item.split('-')[0],
        ptc: item.split('-')[1],
    };
});
  • Related