3

So I'm building a filtering system. I have an array of key-value-pair(kvp) objects and I want to check if a kvp has already been added. If the kvp has I want to remove it, and if it hasn't I want to add it to the array. However I'm having trouble checking deep equality. I can't use an object instead of an array because the keys can be the same (e.g. {state: TX} and {state: NE}). This code doesn't check deep equality so it always pushes a new kvp.

if kvp in filters
    pos = filters.indexOf(kvp)
    filters.splice(pos, 1)
else
    filters.push(kvp) 

I tried this as well, but it also didn't check for deep equality (as well as filters exponentially growing).

if filters.length == 0
    filters.push(kvp)
else
    for filter in filters
        if kvp == filter
            pos = filters.indexOf(filter)
            filters.splice(pos, 1)
        else
            filters.push(kvp)

Any suggestions?

5
  • How complex is the structure of the objects? Commented Feb 5, 2016 at 18:44
  • The objects are very simple, just one property with one value. Commented Feb 5, 2016 at 18:45
  • Just compare that property then. See the duplicate question. Commented Feb 5, 2016 at 18:46
  • @FelixKling The property itself is could be anything, so is there a simpler way than calling getOwnPropertyNames on the filter, checking if that property is not undefined on the kvp, and then comparing the values? Commented Feb 5, 2016 at 18:54
  • How about JavaScript: Get first and only property name of object ? Commented Feb 5, 2016 at 18:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.