0

class LifeCycleComps extends Component {
  constructor(props) {
      super(props);
      this.state = {
        data: 0,
        names: [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }
        ]
      };

      //below is sortAlphabet function
      sortAlphabet = () => {
        this.setState({
          names: this.state.names.sort()
        });
      };


      //sortNames component
      class SortNames extends Component {
        render() {
          return <span > {
            this.props.names.name
          } < /span>;
        }
      }
<button onClick={this.sortAlphabet}>sort</button>
<ul>
  {this.state.names.map((item, i) => (
  <SortNames key={i} names={item} /> ))}
</ul>

Above is my code. I am not sure what is the main problem. In the above code I want to get sorted names by onClick. But I am not getting any positive results from the above snippet. Please let me know folks what I did wrong?

9
  • 3
    Does this answer your question? Sort array of objects by string property value Commented Dec 23, 2019 at 12:01
  • no sir I need solution for reactJs Commented Dec 23, 2019 at 12:03
  • That is a JS solution. It will work in reactjs Commented Dec 23, 2019 at 12:04
  • 2
    Your code doesn't really make sense. You're declaring a class within a class? Commented Dec 23, 2019 at 12:06
  • do your object have any keys rather than "name" in future? Commented Dec 23, 2019 at 12:09

4 Answers 4

2

You can not directly use sort function in array of object. For that you need to write a sort function or write a callback function which you can modify according your need. Here is working code(https://stackblitz.com/edit/react-31un7h) :

import React, { Component } from 'react';
import { render } from 'react-dom';
const SortNames  = (props) =>  {
        return (
           <span > 
            {props.names.name}
         </span>
        )
}
class LifeCycleComps extends Component {
  constructor(props) {
      super(props);
      this.state = {
        data: 0,
        names: [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }
        ]
      };

  }
   compare = ( a, b ) =>  {
      if ( a.name < b.name ){
        return -1;
      }
      if ( a.name > b.name ){
        return 1;
      }
      return 0;
}
  //below is sortAlphabet function
      sortAlphabet = () => {
        this.setState({
          names: this.state.names.sort(this.compare)
        });
      };
      render(){
        return (
          <div>
          <button onClick={this.sortAlphabet}>sort</button>
            <ul>
              {this.state.names.map((item, i) => (
              <SortNames key={i} names={item} /> ))}
            </ul>
          </div>
        );
      }
}



      //sortNames component


class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <LifeCycleComps/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));


Sign up to request clarification or add additional context in comments.

Comments

1

Here is sorted values

let arr = [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }]

function sortIt(x,y) {
  if ( x.name < y.name ){
    return -1;
  }
  if ( x.name > y.name ){
    return 1;
  }
  return 0;
}

arr.sort(sortIt);
console.log(arr);

And here is in reactjs

   sortIt(x,y) {
    if ( x.name < y.name ){
      return -1;
    }
    if ( x.name > y.name ){
      return 1;
    }
    return 0;
  }
  sortAlphabet = () => {
    this.state.names.sort(this.sortIt)
    this.setState({
      names: this.state.names.sort()
    });
  };


  render() {
    return (
      <>
        <button onClick={this.sortAlphabet}>sort</button>
        <ul>
        {this.state.names.map((item, i) => (
        <li key={i} names={item}>{item.name}</li> ))}
      </ul>
      </>
    );

Comments

0

Its to just adapt the javascript code provided in the comments as below.


compare = ( a, b ) => {
  if ( a.name < b.name ){
    return -1;
  }
  if ( a.name > b.name ){
    return 1;
  }
  return 0;
}

     //below is sortAlphabet function
sortAlphabet = () => {
  let objs = [...this.state.names] //create a copy here as you will not want to directly mutate the state by calling sort.
  this.setState({
     names: objs.sort( compare );
  });
};



Comments

0

I've made an StackBlitz in which you could see the solution. Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.