0

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.

1
  • 3
    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 Commented Jul 2, 2018 at 5:28

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

then can you please give some visual code example? i'm still new in javascript.
Jhinel’s answer looks good. Copy that for now, but don’t neglect to study up on why that works/doesn’t work.
0

I think this return is avoiding make a loop of data, it's just taking the first one:

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.

Anyway, I hope it helps. Happy coding! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.