How to map/loop 2 array values to an anchor tag with href and text?

Viewed 559

I am trying to map values from 2 different arrays, one which contains links and the other with tab names. I have an anchor tag which consists of href and text string. Is there a way I can map/loop the values from 2 arrays to supply value. App is built in React.

arrays

const links = ['#all', '#aew', '#roh', '#impact']
const tabnames = ['All', 'AEW', 'ROH', 'Impact']

const classnames = ['One', 'Two', 'Three', 'Four']

code

<a 
 href='#link' 
>
  tabname
</a>

What happens if I try to map 3 arrays on my a, one more for classnames?

code

<a 
 href='#link'
 className='classname'
>
 tabname
</a>
2 Answers

You can use map()

const links = ["#all", "#aew", "#roh", "#impact"];
const tabnames = ["All", "AEW", "ROH", "Impact"];

const output = links.map((el, i) => (<a href={el}>{tabnames[i]}</a>));

You can just use .map() and pass it a function with 2 parameters, the map function can have up to 3 parameters, .map((element, [index], [array]) => ...), index and array are optional, the index can be used to access the element of the 2nd array

Here is a code snipped which should work for you (adjusted to edited answer):

...

{
  links.map((elem, index) => (
    <a href={elem} className={classnames[index]}>{tabnames[index]}</a>
  ))
}

...

If it is possible, I would recommend to combine all your arrays to an array of objects, since all elements with the same index are used together, so combining them would make sense, this would look something like this:

const links = [{
    href: '#all',
    tabName: 'All',
    className: 'One'
  },{
    href: '#aew',
    tabName: 'AEW',
    className: 'Two'
  },{
    href: '#roh',
    tabName: 'ROH',
    className: 'Three'
  },{
    href: '#impact',
    tabName: 'Impact',
    className: 'Four'
}];

...

{
  links.map((el) => (
    <a href={el.href} className={el.className}>{el.tabName}</a>
  ))
}

...
Related