Arp
Arp

Reputation: 1088

How can I keep finding the Max value in an Array and keep incrementing the Max value for a determinate number of times, in a loop?

I want to manipulate an Array during a loop in such a way that I want to:

1 - find current maximum number in the array (would need to keep updating this value during the loop)

2 - push this number adding it to an increment

3 - Perform number 1 & 2 tasks x times, according to my will.

this code can be found here

This is what I am trying to do:

class App extends React.Component {
  state = {
    classesArr: [1581620400000, 1581622800000],
    classesComplete: [1581620400000]
  };

  render() {
    let test = (array, duration) => {
      const min = Math.min(...array);
      let newArr = [min];
      for (let i = 0; i < duration; i++) {
        newArr.push(Math.max(newArr) + 60000);
      }
      return newArr;
    };
    console.log(test(this.state.classesArr, 40));

    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

export default App;

this is the result of my console.log

0: 1581620400000
1: 1581620460000
2: NaN
3: NaN
4: NaN
5: NaN
6: NaN
7: NaN
8: NaN
9: NaN
10: NaN
11: NaN
12: NaN
13: NaN
14: NaN
15: NaN
16: NaN
17: NaN
18: NaN
19: NaN
20: NaN
21: NaN
22: NaN
23: NaN
24: NaN
25: NaN
26: NaN
27: NaN
28: NaN
29: NaN
30: NaN
31: NaN
32: NaN
33: NaN
34: NaN
35: NaN
36: NaN
37: NaN
38: NaN
39: NaN
40: NaN
​```

As you can see ```newArr.push(Math.max(newArr) + 60000)``` is only performed once.

How could I make this work, and have the increment done 40 times

Upvotes: 0

Views: 47

Answers (1)

Saumya gupta
Saumya gupta

Reputation: 391

Use this

newArr.push(Math.max.apply(null, newArr) + 60000);

Upvotes: 1

Related Questions