Home > Blockchain >  Handle object array without duplicates
Handle object array without duplicates

Time:11-28

I use React for my front-end web app. When I call back-end API, I got this array:

[
  {
    id: 1,
    fullname: ABC,
    email: [email protected]
    ...
  },
  {
    id: 2,
    fullname: DEF,
    email: [email protected]
    ...
  },
  {
    id: 2,
    fullname: DEF,
    email: [email protected]
    ...
  },
  {
    id: 3,
    fullname: GHI,
    email: [email protected]
    ...
  },
  {
    id: 1,
    fullname: ABC,
    email: [email protected]
    ...
  }
]

Now, I need to create a new array from this old array but just contain id and fullname and not duplicates. I have try this code:

const oldArray = //this is the array above
const temp = [];
for (let i = 0; i < oldArray .length; i  ) {
    temp.push({
    value: oldArray [i]._id,
    display: oldArray [i].fullname
  });
}
const newArray = Array.from(new Set(temp));

The result I receive:

[
  {
    value: 1,
    display: ABC
  },
  {
    value: 2,
    display: DEF
  },
  {
    value: 2,
    display: DEF
  },
  {
    value: 3,
    display: GHI
  },
  {
    value: 1,
    display: ABC
  }
]

As you can see, the result is still duplicated. How can I fix it?

CodePudding user response:

const tempArray=[];
const filteredArr = oldArray.filter(value =>{
 if(!tempArray.includes(value.id)) {
    tempArray.push(value.id)
    return true
   } 
 })

Create a tempArray, loop over the array and checks if a value exist in tempArr if not push the value into the tempArr and return true(or value)

CodePudding user response:

You can use Array#filter with a Set to store ids that were already found.

const arr=[{id:1,fullname:"ABC",email:"[email protected]"},{id:2,fullname:"DEF",email:"[email protected]"},{id:2,fullname:"DEF",email:"[email protected]"},{id:3,fullname:"GHI",email:"[email protected]"},{id:1,fullname:"ABC",email:"[email protected]"}];
let ids = new Set, res = arr.filter(x => !ids.has(x.id) && ids.add(x.id));
console.log(res);

CodePudding user response:

I know short answer but, use a Set() on the receiving end. Whenever you add an item to a set, use Set.add - it makes sure if it's a duplicate, it won't be added to the set. Sets have similar capability as arrays, but cannot contain duplicates.

  • Related