3

Lets say:

var person = [
    {"classKey": 1, "teacherKey": 1},
    {"classKey": 2, "teacherKey": 1},
    {"classKey": 2, "teacherKey": 1}
]  

How do i prevent the duplicated record to be added, or even how to remove the duplicated combinated pairs?

Thank you

Brian Ruchiadi
  • 331
  • 1
  • 13
  • 29

1 Answers1

4

The main thing you want to do is uniquely identify each entry.

A very quick way would be to concatenate the values into a delimited string, eg

let key = [entry.classKey, entry.teacherKey].join(':')

You could then use this to keep track of existing entries and filter the array. For example, using a Set...

const person = [
    {"classKey": 1, "teacherKey": 1},
    {"classKey": 2, "teacherKey": 1},
    {"classKey": 2, "teacherKey": 1}
]

const filtered = person.filter(function(entry) {
  let key = [entry.classKey, entry.teacherKey].join(':')
  return !this.has(key) && !!this.add(key)
}, new Set())

console.info(filtered)

I'm using a some boolean short-circuiting to keep it brief but if it helps explain what's going on, it works like this

if (set.has(key)) {
  return false // filter out the duplicate value
} else {
  set.add(key) // record the key
  return true // keep this value
}

If you're not keen on using a Set (possibly due to browser compatibility) you could instead keep track using a plain object

const filtered = person.filter(function(entry) {
  let key = [entry.classKey, entry.teacherKey].join(':')
  return !this[key] && (this[key] = true)
}, Object.create(null))
Phil
  • 157,677
  • 23
  • 242
  • 245
  • I havent used this code before.. Hm.. Interesting.. What does the if do? if(this[key]) return false? Means it exists? – Brian Ruchiadi Jun 27 '17 at 02:52
  • @BrianRuchiadi I've change it to use a `Set` to keep track of existing entries. I hope that makes more sense – Phil Jun 27 '17 at 02:53