arunmmanoharan
arunmmanoharan

Reputation: 2675

Map over array of objects and filter based on first name

I have done mapping but it doesn't look good. Can someone advice me on this?

Please advice.

Upvotes: 0

Views: 43

Answers (1)

Abdelkarim EL AMEL
Abdelkarim EL AMEL

Reputation: 1533

Try this :

  class App extends Component {

  render() {
    const titleArray = uniq(data.map((item) => item.name.slice(0, 1)));
    const peopleData = titleArray.map(item => {
      return {
        [item]: data.filter((people) => people.name[0] === item)
      };
    });
    return (
      <div className="app-directory-container">
        <div className="app-directory">
          {titleArray.map(item => {
            return (
              <Fragment key={uniqueId()}>
                <div key={uniqueId()} className="app-directory-separator">{item}</div>
                {peopleData.map((people) => {
                  return (
                    <Fragment key={uniqueId()} >
                      {!isEmpty(people[item]) && people[item].map((item3) => {
                        return (<div className="app-directory-item"> {item3.name} </div>)
                      })}
                    </Fragment>
                  )})}

              </Fragment>
            );
          })}
        </div>
      </div>
    );
  }
}

the <div className="app-directory-item"> should be inside your map.

Working stackblitz

Upvotes: 3

Related Questions