Is there a way to divide the array based on a specific letter in the alphabet using Angular?

I am trying to create something similar to this:

"ABCDEF", "GHIJK", "LMNO", "PRSTU", "VYZXWQ", "0123456789"

I have a list in alphabetical order; I want names starting with "ABCDEF" to be in one array and names starting with "GHIJK" in another.

But I'm unsure of how to accomplish this.

The data I have looks like this:

    [
    {
        "publishDate": "02.08.2022",
        "jobs": [
            {
                "mediaName": "GERCEKTARAF.COM",
                "ids": [
                    {
                        "id": "62ebea1fasfascbd755d317d1ffc9c",
                        "isLocked": false
                    }
                ]
            },
            {
                "mediaName": "MEDYAGAZETE.COM",
                "ids": [
                    {
                        "id": "62ec1asdddc0e45625ab485f38a5",
                        "isLocked": false
                    }
                ]
            },
            {
                "mediaName": "FINANS.GAZETEVATAN.COM",
                "ids": [
                    {
                        "id": "62ecasdasd1dbfe45625ab485f382c",
                        "isLocked": false
                    },
                    {
                        "id": "62ec1dasdasdfc0e45625ab485f3897",
                        "isLocked": false
                    }
                ]
            }
        ]
    }
  ]

(I need the mediaNames under the jobs array to be sorted according to my criteria, regardless of publish date)

Here is my code;

Typescript side:

   getJobsForInternet() {

        this.sidenavService.getInternetJobs().subscribe((jobs: any) => {

            jobs.forEach(getInternetJobs => {

                getInternetJobs.jobs.sort((a, b) => {

                    let _a = a.mediaName
                    let _b = b.mediaName

                    return _a.toString().localeCompare(_b, 'tr', { sensitivity: 'base' });

                })

            });
            this.getJobs = jobs

            console.log(this.getJobs)
        

        });
    }

HTML side:

<nav class="dbt-tree-nav">
    <details *ngFor="let internetJobs of getJobs " class="dbt-tree-nav__item is-expandable">
        <summary class="dbt-tree-nav__item-title">{{ internetJobs.publishDate }}</summary>
        <details class="dbt-tree-nav__item is-expandable">

             ------ I wrote this part by hand for now, but it should be dynamic ------
            <summary class="dbt-tree-nav__item-title">Internet_ABCDEF</summary>
             ------ I wrote this part by hand for now, but it should be dynamic ------

            <details class="last-internet dbt-tree-nav__item is-expandable">
                <summary class="last-internet dbt-tree-nav__item-title">
                    (1) {{internetJobs.jobs.length }}
                </summary>
            </details>

        </details>
    </details>
</nav>

Answer №1

// categorizing strings into groups
const groups = ["ABCDEF", "GHIJK", "LMNO", "PRSTU", "VYZXWQ", "0123456789"]

// generating random data
const data = Array.from({ length: 100 }).map(() => Array.from({ length: Math.random() * 10 | 0 + 1 }).map(() => String.fromCharCode(Math.random() * 26 + 65)).join(''))

// grouping the data based on initial groups
const groupedData = data.reduce((acc, current) => {
  // determining which group the string belongs to
  const group = groups.find(g => g.includes(current[0]))
  acc[group].push(current)
  return acc
}, Object.fromEntries(groups.map(g => ([g, []]))))

console.log(groupedData)

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

Oops! The specified vue-router route name cannot be found

My issue involves a vue component with a method that includes a router push attempting to navigate to another vue component: GetAnimal.vue: ... this.$router.push({ name: "/viewanimal", }); ... The routing mapping is set up like this: router.js: { ...

There seems to be an issue with accessing the 'request' property of an undefined object

Currently, I am in the process of incorporating a base service into an Angular application. This service is designed to provide methods to other services for composing requests with default headers and options. However, I encounter an issue when attempting ...

How can I position text in the top right corner of a v-card's v-img component in Vuetify.js?

I am using Vuetify.js and I am trying to show a single word on the right side of an image within a v-card: <v-card> <v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg" aspect-ratio="2.75"> <span class= ...

When transitioning in Vue, pagination bullets shift to the left upon changing routes

While using Vue 3 and swiper.js, I encountered an issue where the pagination bullets move to the left when the route changes (component unmounted). It appears that the styling for the bullets and active button also disappear. I have created a reproduction ...

Navigation bar not functioning properly due to stickiness

I am currently working on a project where I need to apply a 'fixed' class to a menu when the user scrolls down to that section. While I have successfully implemented this feature, I am facing difficulties in removing the class once the user scrol ...

The function has been called but it did not return a

It seems that there is confusion surrounding the .toHaveBeenCalled() Matcher in Jasmine. While it should return a Promise that resolves when the function has been called, some users are experiencing it returning undefined instead. For example: it('sh ...

Guidelines for integrating a SOAP asmx service into an Angular+8 application using XML implementation

Here is the code snippet I'm struggling with: var xmlItemAll = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x ...

Sending product identification to content_ids for Facebook Pixel tracking

Looking to implement Facebook Pixel for tracking the ViewContent event on product pages. According to Facebook, it's necessary to provide content_ids or contents along with a content_type. I assume that the content_type should always be 'product ...

Enhancing address inputs by using matGoogleMapsAutocomplete while moving the map pin

I am currently in the process of integrating Google Maps into my project using the agmCore npm module. When I enter an address in the input box with the matGoogleMapsAutocomplete directive, the map coordinates are updated and the marker moves on the map. ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Learn the process of updating a specific section of a Facebook share link using AJAX dynamically

Here's an interesting scenario I'm dealing with. I'm trying to create a modification to the Facebook share button link where a portion of the link is replaced by a user ID number. This way, when someone clicks on the shared link, it will dir ...

I can't seem to understand why I am receiving an undefined property when trying to access an

While working with typescript and react within a project created using create-react-app, I encountered an issue during runtime: Cannot read property 'Customer' of undefined. This error occurred while utilizing the following module imports: impor ...

Arrange items in a custom order in Javascript by grouping specific items at the bottom and sorting the rest

My JavaScript challenge involves an array of items like this: [ 'title', 'firstname', 'company', '[m]usr_phone' '[m]usr_city' ] I am looking to implement a custom array sort function that will a ...

Unable to get the Angular Formly select option to bind

I'm currently working on binding formly select type options with the following code: fieldGroup: [ { key: 'TimeOffTypeID', type: 'select', className: 'flex-40 padding-10', templateOptions ...

Is there a way to conceal the parameters in the PHP GET method?

How to convert PHP GET method URL to a cleaner format? example.com/example.php?name=45 to example.com/example.php/45 Is it possible to achieve this using the .htaccess file? ...

Tips for using Firebase Parameterized configuration with Typescript when setting the region() on a Firebase Function

Based on this documentation, I am attempting to utilize a Firebase Parameterized configuration directly within the region() config for a function. My .env file looks like this: LOCATION = 'australia-southeast1'; And my config file is structured ...

What is the best way to remove existing values and update with new values from a JSON using JavaScript?

The following is an excerpt of html code: <div id="prt"> <select name="selectPrt" class="span12" onchange="sta_callPRT();"> <option value="noPrt">Choose one vehicle.</option> <option value="prt1"> ...

Having issues with Craco not recognizing alias configuration for TypeScript in Azure Pipeline webpack

I am encountering an issue with my ReactJs app that uses Craco, Webpack, and Typescript. While the application can run and build successfully locally, I am facing problems when trying to build it on Azure DevOps, specifically in creating aliases. azure ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Utilizing ES6 Functions to Transform Objects into Arrays

Is there a way to convert a JavaScript object into an array using ECMAScript-6? Take, for instance: var inputObj = {a:'foo', b:[1,2,3], c:null, z:55}; The desired outcome would look like this: ['foo', [1,2,3], null, 55] The seque ...