Home > Mobile >  how to get unique names of array of object in javascript
how to get unique names of array of object in javascript

Time:10-11

const employes = [{name:'Rahul Patel'},{name:'Karan Patel'},{name:'Shubham Tayal'},{name:'rahul patel'},{name:'Prakash shah'}];

CodePudding user response:

const arr = [{
  name: 'Rahul Patel'
}, {
  name: 'Karan Patel'
}, {
  name: 'Shubham Tayal'
}, {
  name: 'rahul patel'
}, {
  name: 'Prakash shah'
}];

const uniqueNames = [...new Set(arr.map(e => e.name.toLowerCase()))]

console.log(uniqueNames)

Normalization would be required at your end.

CodePudding user response:

reduce over the objects and check whether there's a match.

const employees = [{name:'Rahul Patel'},{name:'Karan Patel'},{name:'Shubham Tayal'},{name:'rahul patel'},{name:'Prakash shah'}];

const out = employees.reduce((acc, { name }) => {

  // If there's a match return the accumulator
  if (acc.find(el => el.toLowerCase() === name.toLowerCase())) {
    return acc;
  }

  // Otherwise return the updated array
  return [...acc, name];

}, []);

console.log(out);

CodePudding user response:

Use map to extract the name property of each item and Set with spread syntax to get the unique:

const employes = [{name:'Rahul Patel'},{name:'Karan Patel'},{name:'Shubham Tayal'},{name:'rahul patel'},{name:'Prakash shah'}];

const unique = [...new Set(employes.map(e => e.name))]

console.log(unique)

CodePudding user response:

You can use the Array#filter() method in combination with the Array#map() method as in the following demo:

const employes = [{name:'Rahul Patel'},{name:'Rahul Patel'},{name:'Karan Patel'},{name:'Shubham Tayal'},{name:'rahul patel'},{name:'Prakash shah'}];

const uniq = employes.filter((e, i, a) => !a.map(x => x.name.toLowerCase()).slice(0, i - 1).includes(e.name.toLowerCase()));

console.log(uniq);

  • Related