Home > Mobile >  JS Array of object, filter by existing items in same array
JS Array of object, filter by existing items in same array

Time:12-07

I'm trying to filter this array, condition: if programParent property exists in another object id, that object must be ignored. This is what i coded for now, i need some help. Thanks in advance.

let programs = [
    { id: '23', name: 'a', programParent: '111' },
    { id: '24', name: 'a', programParent: '112' },
    { id: '25', name: 'a', programParent: '113' },
    { id: '26', name: 'a', programParent: '24' },
    { id: '27', name: 'a', programParent: '25' },
    { id: '28', name: 'a', programParent: '111' },
    { id: '29', name: 'a', programParent: '28' }
]


let options = programs.filter(x => programs.some(y => y !== x.programParent))
console.log(options)


expected = [
    { id: '23', name: 'a', programParent: '111' },
    { id: '24', name: 'a', programParent: '112' },
    { id: '25', name: 'a', programParent: '113' },
    { id: '28', name: 'a', programParent: '111' }
]

CodePudding user response:

Your filter condition is wrong

programs.filter(x => programs.some(y => y !== x.programParent))

First of all, you probably want to use y.id !== instead of y But also the semantics of some doesn't fit here, because that literally means: "Keep those elements x, where there exists at least one program y with y.id !== x.programParent And that condition is obviously true for every single element, because y.id is different for every element.

Use

programs.filter(x => !programs.find(y => y.id == x.programParent))

instead, which means "Keep those elements x where no element y can be found with y.id == x.programParent

You can also do it with, some but you need to invert the result of some and use a == condition, ie !some(x == y) == none(x == y)

programs.filter(x => !programs.some(y => y.id == x.programParent))

Or you can use every, then you can keep your !== condition, ie ie every(x != y) == none(x == y)

programs.filter(x => programs.every(y => y.id != x.programParent))

To sum up: All three filters I've shown are equivalent. Take the one you like most. But when using some or every you have to be clear about their semantics and how you must define the condtion, so that they fit your needed semantics ...

  • Related