1

How to remove complete record of same object in array please help me this, I am using below funtion but its only remove one value I want remove complete object of same object

var data = [{
    "QuestionOid": 1,
    "name": "hello",
    "label": "world"
}, {
   "QuestionOid": 2,
    "name": "abc",
    "label": "xyz"
}, {
   "QuestionOid": 1,
    "name": "hello",
    "label": "world"
}];

    function removeDumplicateValue(myArray) {
                    var newArray = [];

                    $.each(myArray, function (key, value) {
                        var exists = false;
                        $.each(newArray, function (k, val2) {
                            if (value.QuestionOid == val2.QuestionOid) { exists = true };
                        });
                        if (exists == false && value.QuestionOid != undefined) { newArray.push(value); }
                    });

                    return newArray;
                }

I want result like this

[{
   "QuestionOid": 2,
    "name": "abc",
    "label": "xyz"
}]
DilbertFan
  • 113
  • 1
  • 1
  • 9
JOhns
  • 331
  • 2
  • 4
  • 13
  • 1
    this is not duplicate ... they remove unique value .. i want remove complete both object.. not one – JOhns Mar 10 '19 at 17:57
  • he's not "removing duplicates", he's "removing all duplicated objects leaving _only_ those occurring only once" – Scott Weaver Mar 10 '19 at 19:14

2 Answers2

0

You can use reduce.

var data = [{"QuestionOid": 1,"name": "hello","label": "world"}, {"QuestionOid": 2,"name": "abc","label": "xyz"}, {"QuestionOid": 1,"name": "hello","label": "world"}];


let op = data.reduce((op,inp)=>{
  if(op[inp.QuestionOid]){
    op[inp.QuestionOid].count++
  } else {
    op[inp.QuestionOid] = {...inp,count:1}
  }
  return op
},{})

let final = Object.values(op).reduce((op,{count,...rest})=>{
  if(count === 1){
    op.push(rest)
  }
  return op
},[])

console.log(final)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Do with Array#filter.Filter the array matching QuestionOid value equal to 1

var data = [{ "QuestionOid": 1, "name": "hello", "label": "world" }, { "QuestionOid": 2, "name": "abc", "label": "xyz" }, { "QuestionOid": 1, "name": "hello", "label": "world" }]

var res = data.filter((a, b, c) => c.map(i => i.QuestionOid).filter(i => i == a.QuestionOid).length == 1)
  
console.log(res)
prasanth
  • 22,145
  • 4
  • 29
  • 53