Home > Blockchain >  I want to display an array's information in a specific way. Not sure if possible?
I want to display an array's information in a specific way. Not sure if possible?

Time:08-04

I want to turn this

["Item One", "Item Two", "Item Three", "Item Four", "Item Five", "Item Six"]

into this

"Item One, Item Two... ( 4 Items)"

I already have an ellipsifying function, so you can ignore that. How to display the info with a space and comma in between? and How to add the number of ellipsified items with a ( X Items)?

Sorry if it's not clear. Please lmk if anyone has questions.

Sorry if it's not possible.

CodePudding user response:

array = ["Item One", "Item Two", "Item Three", "Item Four", "Item Five", "Item Six"];
console.log("\""   array[0]   ", "   array[1]   ", "   array[2]   "\""); 
// Prints "Item One, Item Two, Item Three"

You could concatenate it, like this. Here, I've also added an escaped quotation mark at the beginning and end, but you could leave those out if you don't need them. I'm not sure what your "ellipsifying function" entails so I've left it out.

CodePudding user response:

You can try this .

array = ["Item One", "Item Two", "Item Three", "Item Four", "Item Five", "Item Six"];
console.log(`"${array[0]}, ${array[1]}... ( ${array.length - 2} Items) "`); 
// Prints "Item One, Item Two, Item Three"

CodePudding user response:

Is this what you mean?

const array = ["Item One", "Item Two", "Item Three", "Item Four", "Item Five", "Item Six"];
const amountOfElements = array.length;
let formattedText = "";
if (amountOfElements > 2) {
  formattedText = `${array.filter((_, i) => i <= 1).join(", ")}... ( ${amountOfElements-2} Items)`;//?
} else { 
  formattedText = arr.join(", ");
}
console.log({ formattedText });

CodePudding user response:

This question reminds me of a task regarding a React multi-select component I've worked with recently.

I've modified the source code from that task to hopefully help answer your question (although my task and your question are not a 1-to-1 match so my answer would need some slight modifications for your use case).

Hope it helps, cheers!

 const array = [] as string[]
 let textToDisplay: string;

  if (!array.length) {
    textToDisplay = 'No values selected';
  } else if (array.length === 1) {
    textToDisplay = selected[0];
  } else {
    textToDisplay = `${array[0]} ( ${array.length - 1})`;
  }
  • Related