Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Last active April 25, 2020 18:11
Show Gist options
  • Save mojaray2k/70dd02ea66b219aa43ce2857984b71a3 to your computer and use it in GitHub Desktop.
Save mojaray2k/70dd02ea66b219aa43ce2857984b71a3 to your computer and use it in GitHub Desktop.
Using Array.filter Method

Array.filter()

  • The filter() method creates a new array with array elements that passes a test.
  • The filter() method takes a callback function which has 3 arguments:
    • The item value
    • The item index
    • The array itself

In this example I am you looking to simply remove all objects(items in the array) for which a category has already appeared once. You can do this with the Vanilla Javascript filter method. You simply have to use an object to keep count of whether the object has appeared before or not.

var places = [{
    "category": "other",
    "title": "harry University",
    "value": 4788,
    "id": "1"
  },
  {
    "category": "traveling",
    "title": "tommy University",
    "value": 5460,
    "id": "2"
  },
  {
    "category": "education",
    "title": "jerry University",
    "value": 7853456,
    "id": "3"
  },
  {
    "category": "business",
    "title": "Charlie University",
    "value": 6779589,
    "id": "4"
  },
  {
    "category": "business",
    "title": "NYU",
    "value": 0117824,
    "id": "5"
  }
];

function removeDuplicates(arrToBeFiltered, keyToMatch){
  let dups = {};
  return arrToBeFiltered.filter(function(item){ 
    if(item[keyToMatch] in dups){return false;} 
    else {
        dups[item[keyToMatch]] = true; return true;
    }}); 
}

console.log(removeDuplicates(places,'category'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment