0

I am trying to do a simple operation to create an array in React and set it equal to a state object. Anyone know why state.countState is being populated with "null" for each array element? I think I'm missing something very simple here...

class DisplaySort extends Component {
  constructor(props) {
    super(props);
    this.state = {
      array: [5, 4, 3, 2, 1],
      countState: [],
    };
    this.sort = this.sort.bind(this);
  }

 render() {
    return (
        <div className="buttons">
          <button onClick={this.sort}>Sort</button>
        </div>
    );
  }

sort(e) {
    let data = this.state.array;
    let arr = [...data];
    let min = Math.min(...arr);
    let max = Math.max(...arr);

    let i = min,
      j = 0,
      len = arr.length,
      count = [];

    for (i; i <= max; i++) {
      count[i] = 0;
    }

    for (i = 0; i < len; i++) {
      count[arr[i]] += 1;
    }

    this.setState({ countState: count });

};
3
  • 1
    Math.min([5, 4, 3, 2, 1]) returns NaN. Commented Jul 5, 2020 at 20:08
  • What should sort do? It doesn't appear to be sorting the array. Commented Jul 5, 2020 at 20:11
  • This is a truncated version of my application for simplicity. I've narrowed down the (or at least a) problem down to the fact that this returns an array of "null" for count Commented Jul 5, 2020 at 20:30

1 Answer 1

1

Math.min and Math.max doesn't take an array as a parameter.

You can spread the array and pass the values:

const bla = [1,0,-1];

console.log(Math.min(bla)) // logs NaN

console.log(Math.min(...bla)) // logs -1

Update

In this for loop

for (i; i <= max; i++) {
   count[i] = 0;
}

you're looping from 1 to 5 and in each iteration count[i] is set to 0. So that leaves out the first index(0). If you log count after this loop you'll see that the first element is null.

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

2 Comments

Even after adding the spread operator the count array is still populated with "null" elements
@Jerry123 updated my answer, you have a logical error.

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.