Asking
Asking

Reputation: 4172

Don't output same items from array

I'm using react js. I try to map an array with objects and to output the name of each object from array:

const arr = [
  {
    name:"Bill",
    age:88
  },
   {
    name:"Bill",
    age:18
  },
   {
    name:"Jack",
    age:55
  },
]
  {arr.map(i => (
        <li key={i.id}>
          {i.name}
        </li>
   ))}

I want to avoid the same name when i do {i.name}. For this i made this:

{new Set(i.name)}

.. but it does not help. How to avoid displaying the same name in map function?

Upvotes: 1

Views: 43

Answers (3)

palaѕн
palaѕн

Reputation: 73896

You can remove the duplicates from the arr based on the name property in each object and then use array map() method on it like:

{[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (
   <li key={i.id}>
      {i.name}
   </li>
))}

Demo:

const arr = [{name:"Bill",age:88},{name:"Bill",age:18},{name:"Jack",age:55}];

class App extends React.Component {
  render() {
    return (<div>
      {[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (
        <li key={i.id}>
          {i.name}
        </li>
      ))}
    </div>);
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Upvotes: 0

Amila Dulanjana
Amila Dulanjana

Reputation: 1914

you can use lodash to overcome this issue. Following code snippet will easily do what you need.

_.uniqBy(arr,"name").map(i => (
    <li key={i.id}>
      {i.name}
    </li>

))}

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281656

You need to create a Set of names before mapping and rendering. You can do it like below

  {[...new Set(arr.map(i => i.name))].map(i => (
        <li key={i.id}>
          {i.name}
        </li>
   ))}

Upvotes: 1

Related Questions