combine elements from an array into a formatted string and sort them

I'm trying to sort a string based on the length of its items

This is the array

const quotes = [
  {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'}
];

This is the code I have attempted

let i = 0;
let details = '';
for (let index = 0; index < quotes.length; index++) {
 i++;

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

If the data displays like 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 would like to rearrange it by replacing the # with 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 assistance would be greatly appreciated

Answer №1

To find the longest ref1 property length, utilize the map function to extract the lengths of each ref1, then apply Math.max and employ the spread syntax to determine the maximum value in the resulting array.

After obtaining the result, add 4 to it and assign this new value as the target length for 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript and AJAX are showing an error message that says: "ReferenceError: x is not

I am currently working on a jQuery function that retrieves the value from a PHP-generated checkbox and sends it through AJAX. The value being sent is always a single word consisting only of letters. Here is the script I have written: <script type="text ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

What is the best way to integrate qrcode-generator into an Angular 2 application?

I've been trying to implement the qrcode-generator in my app without success, even though it works in plunker. In my app, I am using angular-cli and angular 2.rc-1. Here are the steps to reproduce: ng new newAppName cd newAppName ng serve It work ...

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

The modifications to the URL made by react-router-dom's 'useSearchParams' do not persist when adjusted through the onChange callback of the mui 'Tabs' component

One feature I am looking to implement is a tab navigation component that changes based on a specific search parameter called tab. For instance, if my URL reads as example.com?tab=test2, I want the navigation bar to highlight the item labeled test2. To ac ...

Having trouble with moving a range selector using Cypress code?

I am currently working on a cypress code that is meant to move the range selector from one location to another. While the range selector position is being selected correctly, it fails to actually move the range selector as intended. Below is the command f ...

I'm puzzled as to why, but my code seems to be causing an issue with the command prompt, possibly due

Recently, I've been taking on the challenges of Advent of Code. Day 2 has me stumped, as there's a peculiar issue with the code when running it through node.js in the command prompt: const fs = require("fs"); var valid = fs.readFileSync("inpu ...

Encountering browser freezing issues with a Next.JS app when trying to add an input field

I am currently utilizing Next.JS to construct a form with two inputs. I have followed the traditional React approach for input text reading and validation. "use client" import { firebaseApp } from '@/app/firebase'; import React, { useCa ...

Using Typescript: Compiling specific files within a directory

According to the documentation for typescript, we have the option in tsconfig.json to manage input files using either the files property where all files are listed, or with the exclude property. I have organized all my source files within a directory named ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

Transferring Data from Controller to HTML in AngularJS Version 1

Recently, I started working with angularjs on a new project that involves three main HTML files. The first file is index.html, which contains the ng-view directive. The second file is home.html, where various products are displayed from a database. Each pr ...

JavaScript array object alerts as empty

Having an issue sending a JavaScript array to my PHP as it appears to be empty []. This is not the usual JSON format that I have worked with in the past. Here is an example code snippet: var blah = []; var letters = ['a', 'b', &ap ...

JavaScript featuring Ajax functionality

Although I have limited experience in web programming, I am currently testing a simple add-on to integrate with my app. The webpage I have created displays multiple rows, each containing an editable field for user input. After the user inputs data into th ...

Encountering the error message "Error: Unable to process rejection (TypeError): that.setState function is not defined" while using ReactJS

I've been working on a dynamic chart that changes based on the Slider value. I did some research and everyone suggests that I need to bind it to resolve this error. However, no matter how many times I try to bind the function in different ways, I keep ...

When working with TypeScript, encountering an error involving an array containing an index signature

When attempting to change an object's type to a generic array using the as keyword, I encountered an error. interface TestType { action: TestGeneric<number>[] } type TestGeneric<T> = { [key: string]: T } const func = () => { ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Access a .docx file on my device by utilizing the Microsoft JavaScript API

In my current project, I am developing a Microsoft Word add-in using TypeScript, React, and the Word API. One of the key features of this add-in will allow users to open a document located on their computer, such as "C:\Test\Test.docx", with just ...

extract data from a dropdown menu with playwright

I'm having a tough time figuring out how to select the "All" option in a dropdown menu and extract all the data from that page. I've found some related posts, but they don't quite match my scenario. The "select" element I'm working with ...