Home > Software design >  add data from an array in string and order it
add data from an array in string and order it

Time:10-06

I'm triying to order a string depending on items length

this is the array

var quote = [
  0: {ref1: 'CE255X', price_u: '1024100'},
  1: {ref1: 'M-TK137', price_u: '65400'},
  2: {ref1: '126A‎‎‎', price_u: '242300'},
  3: {ref1: 'M-CE278A', price_u: '35000'},
  4: {ref1: 'M-Q2612A‎‎‎‎‎‎', price_u: '35000'},
  5: {ref1: 'M-Q7551X', price_u: '130002'},
  6: {ref1: '507A', price_u: '905300'},
  7: {ref1: 'M-35A/36A/85A/78A', price_u: '35000'},
]

this is the code that I tried

let i = 0;
let detail = '';
for (let index = 0; index < quote.length; index  ) {
 i  ;

 if (quote[index].ref1.length <= 50) {
   detail  = i   '.'   quote[index].ref1.padEnd(38, '‎‎‎#');
   detail  = quote[index].price_u    '\n';
 }
}
console.log(detail);

If data show this

1.CE255X‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#1024100
2.M-TK137‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎65400
3.126A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎242300
4.M-CE278A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎35000
5.M-Q2612A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎35000
6.M-Q7551X‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎130002
7.507A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎905300
8.M-35A/36A/85A/78A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎35000

I want to order it in this way, replacing the # for white spaces

1.CE255X‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#########1024100
2.M-TK137‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎########65400
3.126A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎##########242300
4.M-CE278A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎#######35000
5.M-Q2612A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎#######35000
6.M-Q7551X‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎#######‎130002
7.507A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎##########905300
8.M-35A/36A/85A/78A‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎‎‎#‎35000

Any help I will appreciate

CodePudding user response:

You can get the length of the longest ref1 property by using map to extract the ref1 length of each item, then Math.max and spread syntax to get the maximum of the resulting array.

Add 4 to the result and set that as the target length when padding:

var quote = [
  {ref1: 'CE255X', price_u: '1024100'},
  {ref1: 'M-TK137', price_u: '65400'},
  {ref1: '126A', price_u: '242300'},
  {ref1: 'M-CE278A', price_u: '35000'},
  {ref1: 'M-Q2612A', price_u: '35000'},
  {ref1: 'M-Q7551X', price_u: '130002'},
  {ref1: '507A', price_u: '905300'},
  {ref1: 'M-35A/36A/85A/78A', price_u: '35000'},
]

let i = 0;
let detail = '';

let maxLen = Math.max(...quote.map(e => e.ref1.length))   4

for (let index = 0; index < quote.length; index  ) {
 i  ;

 if (quote[index].ref1.length <= 50) {
   detail  = i   '.'   quote[index].ref1.padEnd(maxLen, '#');
   detail  = quote[index].price_u    '\n';
 }
}
console.log(detail);

  • Related