Home > Back-end >  render looping string with the index
render looping string with the index

Time:02-22

I'm trying to render the percentage the same as the index

my code

let date = [
  { start_date: '22-2-2022', end_date: '28-2-2022' },
  { start_date: '1-3-2022', end_date: '31-3-2022' },
  { start_date: '1-4-2022', end_date: '30-4-2022' },
];
let arr = [
  { target_amount: 1000 },
  { target_amount: 2000 },
];

let percentage = 5;

date.map((data, index) => {
  return (
    <>
      Date {index 1} = {data.start_date} - {data.end_date}
      {arr.map((trg, idx) => {
        return (
          <>
            {index > 1
              ? `Tier ${idx   1} = ${trg.target_amount}   ${percentage}%`
              : `Tier ${idx   1} = ${trg.target_amount}`}
          </>
        );
      })}
    </>
  );
});

my code output right now like this

Date 1 = 22-2-2022 - 28-2-2022

Tier 1 = 1000
Tier 2 = 2000 


Date 2 = 1-3-2022 - 31-3-2022

Tier 1 = 1000   5%
Tier 2 = 2000   5%


Date 3 = 1-4-2022 - 30-4-2022

Tier 1 = 1000   5%
Tier 2 = 2000   5%


What I'm expected is something like this, the 5% will add following the index of the date.
I tried to render it but I cant figure it out

Date 1 = 22-2-2022 - 28-2-2022 

Tier 1 = 1000
Tier 2 = 2000 


Date 2 = 1-3-2022 - 31-3-2022

Tier 1 = 1000   5%
Tier 2 = 2000   5%


Date 3 = 1-4-2022 - 30-4-2022

Tier 1 = 1000   5%   5%
Tier 2 = 2000   5%   5%


Any help is appreciated, Thank you

CodePudding user response:

Something like this?

const percentageString = `   ${percentage.toString()}%`.repeat(index)

In your outer loop, and then refer to that value in the inner loop.

Ex:

percentage = 5

index = 0

result ''


index = 2

result = ' 5% 5%'

CodePudding user response:


date.map((data, index) => {
        return (
          <>
            Date {index   1} = {data.start_date} - {data.end_date}
            {arr.map((trg, idx) => {
              let p = "";
              for (var i = 0; i < index; i  ) {
                p  = `   ${percentage}%`;
              }
              return (
                <div>
                  {index > 0
                    ? `Tier ${idx   1} = ${trg.target_amount}`   p
                    : `Tier ${idx   1} = ${trg.target_amount}`}
                </div>
              );
            })}
          </>
        );
      })

  • Related