Jerry123
Jerry123

Reputation: 67

State array not populating in React

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 });

};

Upvotes: 0

Views: 134

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

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.

Upvotes: 1

Related Questions