How can I map over two arrays at the same time?
Using the second parameter of map
, which is the index of the current element, you can access the correct element of the second array.
const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ];
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]
const players = link.map((value, index) => {
const linkContent = content[index];
return (
<div>
<Reactplayer url="{value}" />
<ControlLabel>{linkContent}</ControlLabel>
</div>
);
});
This is the perfect candidate for the zip
method which is available with various libraries, such as Lodash or Rambda, if you have one of those in your project.
const players = _.zip(link, content).map((value) => {
return (
<div>
<Reactplayer url="{value[0]}" />
<ControlLabel>{value[1]}</ControlLabel>
</div>
);
});
Can we map over two arrays at same time in js?
Assuming, the projectText and imageUrl contain the elements in order and have the same number of elements, you can simply access the url from imageUrl
array using the index from projectText
<div ClassName="container">
{projectText.map((project, index) => (
<div key={index} className="project">
<h3>{project}</h3>
<img key={index} src={`../img/${imageUrl[index]}.png`} alt={project}/>
<a role="button" className="btn" href={`https://${project}`} target="_blank" rel="noopener noreferrer">Github</a>
</div>
</div>
))}
{/* experiment train */}
Mapping two arrays at same time
I did a small refactoring of your code. For explanation see comments:
renderCars(){
// make sure to really access your cars array
const list = this.state.data[0].Cars.map( (item, index) => {
const color = this.state.color[index];
// render Modelname and color side by side
return (
<View key={index} style={{flexDirection: 'row'}}>
<View style={{width: 15,height: 15,borderRadius: 5, backgroundColor: color }} />
<View>
<Text style={{fontSize:12, paddingBottom:12, color:'gray'}}>{item}</Text>
</View>
</View>
)
});
return list;
}
render(){
return (
<View style={styles.container}>
{this.renderCars()}
</View>
);
}
Here is a complete working example:
https://snack.expo.io/@tim1717/sponaneous-croissant
Edit: Explanation about modulo operator:
The modulo operator is a mathematical function. Here we can make sure that we only access indices inside the array which really exist.
Here are some examples:
1 % 3 = 1
3 % 3 = 0
4 % 3 = 1
For your example the modulo operator is not necessary, but it is a good idea to use it. Especially if you have more cars than colors and you want to reuse the colors
Using map to iterate through two arrays
If at all possible, I would recommend storing the text alongside the images in an array of objects, eg:
const objects = [{text: 'abc', image: '/img.png' }, /* others */];
that way you can just iterate through the array and select both members at the same time, for example:
objects.map(item => (<Component icon={item.image} text={item.text} />) )
If this isn't possible then just map over one array and access the second array's members via the current index:
sentences.map((text, index) => {
const image = images[index];
return (<Component icon={image} text={text} />);
});
Map over two arrays of objects, match properties and store specific info in a new array
You can use find() inside map() to find the element. This finds the element even if they aren't at the same index in both arrays.
Then use filter() to filter any undefined
values which will be present if there isn't a match.
var arrNames = [ {name: "A"}, {name: "B"}, {name: "C"}];
var arrInfo = [ {name: "A", info: "AAA"}, {name: "B", info: "BBB"}, {name: "C", info: "ccc"}];
let result = arrNames.map(x => { item = arrInfo.find(item => item.name === x.name); if (item) { return item.info; } }).filter(item => item !== undefined); // Can also use filter(item => item);
console.log(result);
Javascript: Map values of two arrays in a new array
Got it working:
const finalData = data.map(dataItem => {
dataItem.condition = dataItem.condition ? rulesMap[dataItem.condition] : null;
dataItem.helpers.map(item => {
item.condition = item.condition ? rulesMap[item.condition] : null
})
return dataItem;
});
How to join two arrays in a map function?
Altghough it is still not very clear from the screenshots (always prefer to use text and not images for data/code), it looks like you want
const onFinish = (values) => {
const updatedValues = values.fields.map((field, index) => ({...field, index}));
console.log( updatedValues );
}
Map multiple arrays at the same time javascript/reactjs
Try to modify your updateWeekDays
function like below:-
const updateWeekDays = () => {
const copyWeekDay = [...weekday];
return copyWeekDay.map(week => {
week.sortedDays = week.sortedDays.map(day => {
if (day.dayNum === selectedDay.dayNum) {
day.chosen = !day.chosen;
}
return day;
});
return week;
});
};
Related Topics
Using Thymeleaf Variable in Onclick Attribute
Concatenate Json to a String in JavaScript
Image Taken from Camera Not Saved to Gallery
Onclick JavaScript to Make Browser Go Back to Previous Page
How to Bind on Click Event on Dynamically Created Button in Angular 6
React Jsx - Make Substring in Bold
Detect If a Field Is Updated With JavaScript or Jquery
How to Remove Special Character from Json Without Parsing
How to Prevent Ajax Requests to Follow Redirects Using Jquery
Save State When Refresh Page - Reactjs
Angular 4: How to Read Content of Text File With Httpclient
How to Set Image to Fit Width of the Page Using Jspdf
Why Does This Onclick Event Not Work in an HTML Iframe
Determine If String Is in Base64 Using JavaScript
Call Function Onpress React Native
How to Properly Import Function in a Reactjs File