1

I have remove duplicate function this will remove duplicate record. But I want atleast one copy of that.

Ex:

var myArr = [{"Country":"China","Rank":"2"},{"Country":"USA","Rank":"2"},{"Country":"China","Rank":"2"}];

O/P = [{"Country":"China","Rank":"2"},{"Country":"USA","Rank":"2"}] 

I am deleting on basis of "Country".

My Code

removeDuplicates : function(myArr, Country) {
        var finalArray = [];
        var values = [];
        var value;
        for (var i = 0; i < myArr.length; i++) {
            value = myArr[i][Country];

            if (values.indexOf(value) === -1) {
                finalArray.push(myArr[i]);
                values.push(value);
            }
        }
        return finalArray;
    },

How to maintain original record and remove only duplicate.

David
  • 4,266
  • 8
  • 34
  • 69
  • 2
    Possible duplicate of [Remove duplicates from an array of objects in javascript](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – Jeremy Thille Nov 24 '17 at 10:18

2 Answers2

0

Try something like this

var result=[];
myArr.map(function(x){
          if(myArr.filter(y=>y.Country==x.Country).length==1 || (result.filter(r=>r.Country==x.Country).length==0))
          result.push(x);
})
console.log(result);
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40
0

I would use reduce & find here.

const myArr = [{"Country":"China","Rank":"2"},{"Country":"USA","Rank":"2"},{"Country":"China","Rank":"2"}];

const newArr = myArr.reduce((prev, cur) => {
   if (prev.find((i) => i.Country === cur.Country)) return prev;
   prev.push(cur);
   return prev;
}, []);
Jake Lacey
  • 623
  • 7
  • 24