var stu_names = ['Jhon','Alice','Mik'];
var stu_score = [300,200,400];
for (var i = 0; i < stu_names.length; i++) {
for(var j = 0; j < stu_score.length; j++) {
console.log(`Score of ${stu_names[i]} is ${stu_scrore[j]}`);
}
}
I want to get the result like
'Score of Jhon is 300' 'Score of Alice is 200' 'Score of Mike is 400'
But instead of it, I m getting this result
Score of Jhon is 300
Score of Jhon is 200
Score of Jhon is 400
Score of Alice is 300
Score of Alice is 200
Score of Alice is 400
Score of Mik is 300
Score of Mik is 200
Score of Mik is 400
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
concat() can be used to merge multiple arrays together. But, it does not remove duplicates.
There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays: Merge without removing duplicate elements. Merge after removing the duplicate elements. Merge without removing duplicate elements: We will first begin with three arrays and merge them.
In the following example, instead of the spread operator, array.concat () method is used to join two arrays. In the following example, spread operator is used to join two arrays.
But we can join arrays much more easily by using spread operator. Lets' try to merge arrays without spread operator. In the following example, instead of the spread operator, array.concat () method is used to join two arrays. In the following example, spread operator is used to join two arrays.
Using concat () Method: The concat () method accept arrays as arguments and returns the merged array. Using spread operator: Spread operator spreads the value of the array into its constituent elements.
You need to take the same index for getting the same values of different arrays.
var stu_names = ['Jhon', 'Alice', 'Mik'];
var stu_score = [300, 200, 400];
for (var i = 0; i < stu_names.length; i++) {
console.log(`Score of ${stu_names[i]} is ${stu_score[i]}`);
}
You can use one for loop
while making sure that both arrays have the same length:
var stu_names = ['Jhon','Alice','Mik'];
var stu_score = [300,200,400];
if(stu_names.length == stu_score.length){
for(let i = 0; i < stu_names.length; i++)
console.log(`Score of ${stu_names[i]} is ${stu_score[i]}`);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With