0

im just trying to figure out how could i remove from an array of objects all elements which are of same type, might be weird, but lets say i have this array:

arrayX=[
{id: 5, turnName: "10_00_am"}
{id: 5, turnName: "10_00_am"}
{id: 6, turnName: "11_00_am"}
{id: 6, turnName: "11_00_am"}
{id: 7, turnName: "12_00_am"}
{id: 8, turnName: "01_00_pm"}
]

thus according with this and according with what i want to do the result might be like

arrayResult=[

{id: 7, turnName: "12_00_am"}
{id: 8, turnName: "01_00_pm"}
]

i mean , not only deleting duplicated , but also the ones which were compared with those duplicated.

I have tried several ways , including filters , or set , but all of this results , always throws me a array of objects with unique values (which is ok but not in this case for this specific requirement).

the latest way i tried was this:

arrayResult = arrayX.filter((elem, index, self) => self.findIndex(
    (t) => {return (t.id === elem.id && t.turnName === elem.turnName}) === index)

Any help about how could i solve this issue Thanks!!!

Enrique GF
  • 1,215
  • 3
  • 16
  • 35

1 Answers1

1

You can do something like this:

var arrayX=[
{id: 5, turnName: "10_00_am"},
{id: 5, turnName: "10_00_am"},
{id: 6, turnName: "11_00_am"},
{id: 6, turnName: "11_00_am"},
{id: 7, turnName: "12_00_am"},
{id: 8, turnName: "01_00_pm"}
]
var newArray = arrayX.map(i=> JSON.stringify(i));
var res = newArray.filter((elem, index)=>{
  if(newArray.indexOf(elem) === newArray.lastIndexOf(elem)){
    return elem
  }
});
var finalResult = res.map(i=>JSON.parse(i));
console.log(finalResult)
ABGR
  • 4,631
  • 4
  • 27
  • 49