0

I have the following component that is displaying a list from my database. The list is displaying correctly as I want, so the newest element is on top rather than the bottom.

How do I limit my list to display only the 7 last newest elements ?

slice(0,7) show the elements from the bottom so it's not working on reverse()

render() {
  return (
    <div>
      <TransitionGroup>
      
        {this.state.patients.slice(0).reverse().map(patient => 
        
          <CSSTransition 
            key={patient.id}
            timeout={500}
            classNames="item">
            
            <ListGroup.Item>                 
              {patient.nom}  {patient.prenom}  
            </ListGroup.Item>  
          </CSSTransition>
        )} 
      </TransitionGroup>
    </div>
  )
}
Christian Fritz
  • 18,961
  • 3
  • 42
  • 63
BronzeJamie
  • 51
  • 1
  • 8

2 Answers2

3

Instead of passing a positive index to slice you could pass a negative index and slicing will happen from the end of the array.

let abc = [1,2,3,4,5,6,7,8,9,10]

let fromStart = abc.slice(0,7)

let fromEnd = abc.slice(-7)

console.log('Start Element', fromStart)
console.log('End Elements', fromEnd)

You can change your slicing in this form.

this.state.patients.slice(-7).reverse().map
Rajiv Punjabi
  • 416
  • 3
  • 4
2

Not sure where you previously tried the slicing, but if you do it after the reverse it works as intended (showing the first 7 items of the, then, correctly sorted list):

this.state.patients.slice(0).reverse().slice(0,7).map(patient =>
...
Christian Fritz
  • 18,961
  • 3
  • 42
  • 63