1

I have come across an issue in which there is a hash which contains a label, index, visible and I need to order the component according to the index value, it should be visible if visible is true.

These are my components:

render(){
  return(
    <GroupFeaturedCarousel {...this.props}/>
    <GroupAssignmentCarousel {...this.props}/>
    <GroupSharedCarousel {...this.props}/>
    <GroupChannelCarousel {...this.props}/>
  )
}

and array of hashes is this:

myArray = [
{default_label: "Featured", index: 0, visible: true},
{default_label: "Assigned", index: 1, visible: true},
{default_label: "Shared", index: 2, visible: true},
{default_label: "Channels", index: 3, visible: true}]

All I can think of solving this is by using _.sortBy(myArray, 'index') but then how can I implement this?

Need to consider sort and visible both.

vikas95prasad
  • 1,234
  • 1
  • 12
  • 37
  • Could you elaborate on what you want? Do you want to sort by visibility as well as index? If so, then [this post](https://stackoverflow.com/questions/16426774/underscore-sortby-based-on-multiple-attributes) should help – ManavM Feb 04 '19 at 08:11
  • No, I just want to order the component according to the myArray index. Will add the visibility later. – vikas95prasad Feb 04 '19 at 08:12

2 Answers2

2

What do you mean by 'hash'? Did you mean an array?

I would something like this if i understand you correctly:

class X extends React.Component{
  myArray = [{ 
      component: GroupFeaturedCarousel,
      index: 0, 
      visible: true
    }, {
      component: GroupAssignmentCarousel,
      index: 1, 
      visible: true
    }
  ]
  
  render() {
    return this.myArray
    .filter(x => x.visible == true)
    .sort((a,b) => a.index - b.index)
    .map(({component: Component, index}) => ({
       <Component key={index} {...this.props} />
    });
  }
}
r g
  • 3,586
  • 1
  • 11
  • 27
2

Extend your array item to look like this:

{
   default_label: 'foo',
   index: 0,
   visible: true,
   component: FooComponent
}

Then render like this:

render() {
    return <React.Fragment>
       { myArray
           .filter(item => item.visible)
           .sort((a,b) => a.index - b.index))
           .map(item => {
                const Component = item.component
                return <Component {...this.props} key={item.index} />
            }) }
    </React.Fragment>
}
thedude
  • 9,388
  • 1
  • 29
  • 30