0

I have following code for remove duplicate record. It shows me unique values and removes the last duplicate record. However, what I want is, if two passports are the same, remove both elements from the array.

Example

var array = [{
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss",

  },
  {
    "PassportNo": "abced",
    "Name": "John"

  }
];


function removeDuplicates(originalArray, objKey) {
  var trimmedArray = [];
  var values = [];
  var value;

  for (var i = 0; i < originalArray.length; i++) {
    value = originalArray[i][objKey];

    if (values.indexOf(value) === -1) {
      trimmedArray.push(originalArray[i]);
      values.push(value);
    }
  }
  return trimmedArray;
}

var noDuplicates = removeDuplicates(array, 'PassportNo');
console.log(noDuplicates);
/*
[
  {
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss"
  }
]
*/

I want like this (remove both values):

[{
  "PassportNo": "abcederrr",
  "Name": "Johnss"
}]
10
  • var removedublicate == is comparation, just use one '=' for assignation. Can you also edit it with your result please? Commented Oct 18, 2018 at 22:07
  • its mistake. sorry.... Commented Oct 18, 2018 at 22:11
  • @HereticMonkey it's similar but not a duplicate. OP wants to remove all instances of the item if there is a duplicate, not just the duplicate instance. Commented Oct 18, 2018 at 22:18
  • 1
    That was not at all clear from the text. You may want to edit the text to make that more clear. Commented Oct 18, 2018 at 22:19
  • 1
    I edited your question a bit to make it easier to understand. I removed the AngularJS stuff, because it doesn't really matter to the array question, and it's easier to reproduce without having to build out a controller :). Commented Oct 18, 2018 at 22:29

1 Answer 1

3

You can do this with a simple filter after storing counts in a separate object (i.e. only choose passports that have count 1).

var array = [{
    "PassportNo": "abced",
    "Name": "John"
  },
  {
    "PassportNo": "abcederrr",
    "Name": "Johnss",
  },
  {
    "PassportNo": "abced",
    "Name": "John"
  }
];

var passportCounts = array.reduce((map, curr) => {
  if (curr.PassportNo in map) map[curr.PassportNo] += 1;
  else map[curr.PassportNo] = 1;
  return map;
}, {});

console.log(array.filter(p => passportCounts[p.PassportNo] === 1));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.