typescript method searching for and merging all keys starting with the specified prefix

Take a look at this object:

https://i.sstatic.net/V0xvI.png

Where each property in system(1) holds tridimensional coordinates. Is there a more efficient method to consolidate properties with the same prefix without nesting loops within loops? My goal is to accomplish the following:

// Coordinates of points in systems prefixed with lwb
setOfValidPoint1 = [[3.370316528, 0.050628689000000004, 0.20987313800000001], 
                    [3.4050299070000003, 0.559079376, 0.267691772], 
                    [2.990670776, 0.05074561700000001, 0.21216622899999998]]

// Coordinates of points in systems prefixed with lwb
setOfValidPoint2 = [[3.440000732, 0.04970323, 0.210814064], 
                    [3.4748417970000003, 0.5596490780000001, 0.268024719]]

// Coordinates of points in systems prefixed with mrf (one point)
setOfValidPoint3 = [[3.51507, 0.777428, 0.36277]]

And so on...

Answer №1

When you utilize the reduce() method, you're essentially avoiding direct loops (even though there's an internal iteration loop over the input data):

function mergeData(data: { [key: string]: number[] }) {

    return Object.getOwnPropertyNames(data).reduce((accumulator, key) => {

        const prefix = key.split('_')[0];

        if (accumulator[prefix] === undefined) {
            accumulator[prefix] = [];
        }

        accumulator[prefix].push(data[key]);

        return accumulator;

    }, {} as {[key: string]: number[][] })
}

Here's a practical example:

const inputData = {
    a_xx: [1, 2, 3],
    b_xx: [9, 8, 7],
    a_yy: [11, 22, 33],
    b_yy: [9, 8, 7],
    c: [9, 8, 7],
};

function mergeData(inputData) {

    return Object.getOwnPropertyNames(inputData).reduce((accumulator, key) => {
    
        const prefix = key.split('_')[0];
        
        if (accumulator[prefix] === undefined) {
            accumulator[prefix] = [];
        }
        
        accumulator[prefix].push(inputData[key]);
        
        return accumulator;
        
    }, {});
}

console.log(mergeData(inputData));

Answer №2

It's difficult to say if this meets your exact requirements without more information, but here is a sample solution utilizing just one loop.

class SampleClass{
    item1: number[] = [2.9102, 0.0346, 0.1834];
    item2: number[] = [2.9456, 0.5598, 0.2493];
    object1: number[] = [3.1074, 0.6789, 0.2536];
    object2: number[] = [3.0623, 0.0452, 0.1979];
}

let sample = new SampleClass();

let itemList: number[][] = []
let objectList: number[][] = []

for(var key in sample){
    if(sample.hasOwnProperty(key)){
        let name_segments: String[] = key.split('');
        switch(name_segments[0]){
            case "item":
                itemList.push(sample[key]);
                break;
            case "object":
                objectList.push(sample[key]);
                break;
            default:
                console.log("Unexpected property found")
                break;
        }
    }
}

console.log("Items List");
console.log(itemList);
console.log("Objects List");
console.log(objectList);

The output generated by the above script is:

Items List
[ [ 2.9102, 0.0346, 0.1834 ], [ 2.9456, 0.5598, 0.2493 ] ]
Objects List
[ [ 3.1074, 0.6789, 0.2536 ], [ 3.0623, 0.0452, 0.1979 ] ]

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

Opening a new tab in Angular 6 from a component with freshly generated HTML (containing input data)

Hello everyone. I have a requirement where I need to open a new browser tab with formatted input data from a modal component. Here's an example code snippet that attempts to achieve this using ng-template: @Component({ template: '< ...

A step-by-step guide on how to simulate getMongoRepository in a NestJS service

Struggling with writing unit tests for my service in nestjs, specifically in the delete function where I use getMongoRepository to delete data. I attempted to write a mock but couldn't get it to work successfully. Here is my service: async delete( ...

Using TypeScript to implement a nested static class with enforced generic type constraints

As an illustration, let's consider a basic linked list class in TypeScript version 3.7.5. A LinkedList<T> is composed of a series of ListNode<T>, where the type variable T remains consistent between them. In this scenario, a private static ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

Child stateless component in React receiving outdated props from parent Class component

Within my Parent Component, there is a form that users interact with. The form displays real-time information that updates as fields are edited. However, I am encountering an issue where the child component sometimes receives outdated props from the previo ...

Using React-Router-Native to send an image as a parameter

I am encountering an issue while attempting to pass an image as a parameter in react-router-native and retrieve the data from location.state. Typically, I use the following code to display an image: import Icon from '../image/icon.png'; <Vie ...

Creating a unique encryption code using OpenSSL for an array value that is unable to be decrypted

Any valuable input from team members is highly appreciated. I've just started the process of encrypting data stored in MySQL database tables. This involves learning how to encrypt values within a 2-dimensional array that will eventually be uploaded i ...

Extracting IDE autocomplete in a Vue.js component can greatly improve your workflow and efficiency

Currently, I am in the process of developing a component library for the organization where I work. To achieve this, I am utilizing vuetify in combination with vue.js. One of the tasks at hand is to create custom components such as company-autocomplete, w ...

Upon selection, the first parameter is detected as undefined

I am dealing with a dropdown button that has an event handler: onSelect={this.handleSelect.bind(this)}> However, the first parameter I receive is undefined and the second parameter is a Proxy object with information about the event. I am confused as t ...

Navigating through the properties of an object within an array using Angular

In my AngularJs project, I am utilizing the ng-repeat option to display the questionText property within each object in an array. [{ "_id": "57fa2df95010362edb8ce504", "__v": 0, "answers": [], "options": [], "questionText": "what is yo ...

What is the process for importing a TypeScript file as a library?

My customized personal "library," dubbed methlib and saved as a .ts file on my computer, contains a plethora of classes, interfaces, functions, and more that I frequently use and prefer to keep in one convenient location. The dilemma I face now is how to u ...

Change the first `m` elements of a given array

I am working with an array of length n. My goal is to replace the first m<n elements with 0. Currently, I have written a simple for loop to accomplish this task: m<-100 n<-1000 x<-runif(n) for(i in 1:m){ x[i]<-0 } However, I am curious i ...

Mean value calculated for each hour within a given array

Every minute, my array updates. To show the daily average of each hour, I need to calculate the average for every 60 elements. The latest minute gets added at the end of the array. // Retrieving the last elements from the array var hours = (this. ...

The string property I pass to the List component with the flexDirection style is meant to be implemented, but unfortunately, an error occurs

When passing a string property ("raw" | "column") to the List component which has a flexDirection style property, I encounter an error: Type '{ direction: String; }' is not assignable to type 'FlexDirection | undefined'. 7 | ...

How to retrieve the last non-empty element from an array in PHP?

I'm facing a problem with the PHP Array. I need to extract the last element from an array that is neither null nor blank. $string = '9580 County Road Clarence Center, New York 14032 TEL: 716-86 ...

Show method created by function, substituting the former element on the display

showButtons(1) will show radio buttons for frame number 1, showButtons(400) will display radio buttons for frame number 400. The current code shows all radio buttons for every frame up to 400 HOWEVER, I am aiming for a single set of radio buttons to start ...

The parameter label is being detected as having an any type, as specified in the Binding element 'label'

Currently, I am referencing an example code snippet from react-hook-form. However, upon implementation, I encounter the following error: (parameter) label: any Binding element 'label' implicitly has an 'any' type.ts(7031) The example c ...

Can you explain the functionality of this particular line of code in JavaScript?

As I continue to practice my coding skills, despite still being relatively new, I often come across this type of code in loops when searching for solutions to practice problems. I am intrigued by what exactly this particular line of code is accomplishing. ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...

Using Numeric Values as Array Keys

Here is an example array $products: Array ( [0] => Array ( [id] => 2488 [va] => 1526 ) [1] => Array ( [id] => 19512 [va] => 286 ) [2] => Arra ...