Two arrays in a loop with JavaScript

Multi tool use
Two arrays in a loop with JavaScript
I have a problem in my script. I have two arrays, which is the data and also a month.
What I want is that to append two merge the month in data, but then only 1 value shows in month, here is my code:
const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
ali_fcr.get().then((d) => {
let store = '';
let getTotal = d.reduce(function(x, y) {
return (x * 1) + (1 * y);
});
let new_array = d.map((data) => {
for (let i = 0; i < data.length; i++) {
return '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>';
}
});
new_array.unshift('<td>Case Receive</td>');
new_array.push('<td style="color:red; text-align:center;">' + getTotal + '</td>');
new_array.forEach((data) => {
store += data;
});
_doc.querySelector('tr[data-alicase-category="cr"]').innerHTML = store;
});
but the result in my html is only january
value of month.
january
for(let i =0; i < 1000; i++) { return i; }
2 Answers
2
I think this return is avoiding make a loop of data
, it's just taking the first one:
data
let new_array = d.map((data) => {
for(let i = 0; i < data.length; i++) {
return '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>';
}
});
I suggest you to keep with array functions like:
let new_array = d.map(data => data.map(
(d_data, i) => '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>'));
Also, I don't know how data
is structured, so I have no idea if you want to push inside <td>
the value of d_data
instead of data
.
data
<td>
d_data
data
Anyway, I hope it helps. Happy coding! :)
Jaromanda X said it in the comments, but it’s your for loop inside a function making use of the return keyword. Non-function blocks (ex: if, while, for) do not return anything, so calling return will “bubble up” to the function scope, in this case causing your map function to return after only one iteration.
Solution: consider pushing that html string into an array, then returning htmlarray.join(‘’)
out of the map function. Now your loop can complete and the data will be returned together.
htmlarray.join(‘’)
then can you please give some visual code example? i'm still new in javascript.
– kim nicole sabordo
Jul 2 at 5:51
Jhinel’s answer looks good. Copy that for now, but don’t neglect to study up on why that works/doesn’t work.
– Ben Steward
Jul 2 at 5:56
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
think carefully what having a return in a for loop means .... or simply
for(let i =0; i < 1000; i++) { return i; }
- how many iterations does this loop go for– Jaromanda X
Jul 2 at 5:28