0

trying to create a button in the component that sorts the array of objects by each objects name alphabetically and renders in component when clicked

menuItems = [{name: pizza}, {name: burger}]
class MenuItems extends Component {

    handleclick = (item) => {
        this.props.deleteMenuItem(item.id);
    }

    render(){
        return ( 
            <div>
                <button onClick={this.handlechange}>filter a to z</button>
                {this.props.menuItems.map((item) =>(
                    <li class="list" key={item.id}>
                        {item.name}
                        <br></br>
                        {item.body}
                        <br></br>
                        <img src={item.image}></img>
                        <br></br>
                        <button id={item.id} onClick={() => this.handleclick(item)}>delete </button>
                    </li>
                ))}

            </div>
        )
    }
}

export default connect(null, {deleteMenuItem})(MenuItems)```
sam
  • 1
  • 3
  • 1
    I don't see any code which is trying to sort anything. – takendarkk Oct 15 '21 at 20:13
  • Have you written the `handleChange` function? You should add that code to your question. – Andy Oct 15 '21 at 20:13
  • new to react n javascript , first time asking a question on stack, guess i should ask how to start the process of the first question – sam Oct 15 '21 at 20:20
  • duplicate check https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript – scr2em Oct 15 '21 at 20:26

1 Answers1

2

you could try this

menuSort = () => {
const newMenuItems = { ...this.props.menuItems };
newMenuItems.sort((a, b) => a.name.localeCompare(b.name));
this.setState({MenuItems: newMenuItems });
};

The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

then use MenuItems in your render function, like you already have

taha maatof
  • 1,862
  • 2
  • 9
  • 23