Emo
Emo

Reputation: 620

Sort mapped list with Lodash on ReactJS

I have an array:

people = [
  {
    name: "Kyle",
    _id: "2"
  },
  {
    name: Susan,
    _id: "1"
  }
]

I have a mapped list as such:

return (
  <ul>
    {people.map( (person) => {
      return (
        <li>
          <span>{person.name}</span>
          <span>{person.id}</span>
        </li>
       )
    })}
  </ul>
)

This is all working well, but how can I sort them, say based on "name"? I tried to use the [_.sortBy][1] but couldn't figure out how it would fit to the context of React and map function. Using lodash, or underscore's _.sortBy would be appreciated.

Thanks!

Upvotes: 4

Views: 10963

Answers (3)

Hayk Aghabekyan
Hayk Aghabekyan

Reputation: 1087

You need to import it first

import sortBy from "lodash/sortBy";

And then you can use it like

const arr = [{id: 2}, {id: 0}];
sortBy(arr, "id");

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

In _.sortBy you can pass the name of the field that will be used for sorting your collection, read more about _.sortBy

var Component = React.createClass({
    getInitialState() {
        return {
            people: _.sortBy([
                { name: "Kyle", _id: 2}, 
                { name: "Susan", _id: 1}
            ], '_id')
        }
    },

    sortBy(field) {
        this.setState({ 
            people: _.sortBy(this.state.people, field) 
        });
    },

    render: function() {
        var peopleList = this.state.people.map( (person, index) => {
            return (<li key={index}>
                <span>{person.name}</span>
                <span>{person.id}</span>
            </li>);        
        })

        return <div>
            <a onClick={this.sortBy.bind(this, '_id')}>Sort By Id</a> | 
            <a onClick={this.sortBy.bind(this, 'name')}>Sort By Name</a>
            <ul>{peopleList}</ul>
        </div>;
    }
});

Example

Upvotes: 8

jdinhify
jdinhify

Reputation: 86

You can use the sortBy like this:

_.sortBy(<array name here>, '<key here>')

Try

return (
    <ul>
        {_.sortBy(people, 'name').map( (person) => {
            return (
                <li>
                    <span>{person.name}</span>
                    <span>{person.id}</span>
                </li>
            )
        })}
    </ul>
)

Upvotes: 3

Related Questions