Filter an array of objects based on a specific key-value pair using TypeScript

I am currently working on displaying objects by filtering them in my program. Upon receiving an array of objects, each containing key-value pairs, I aim to order this array based on a specific key.

For example, here is the structure of one object:

Object {
​​
assembly_id: 1234
​​
installation_id: "29537"
​​
interval: "600"
​​
itedef_id: "239"
​​
item_id: "14485"
​​
object_id: "114"
​​
name: "moa"
​​
}
​​

My objective is to rearrange the array into arrays of objects sorted by 'object_id'. To achieve this, I have implemented a function called transformArray which groups the objects based on the specified field:

transformArray(array: Array<any>, field: string) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }

This function successfully provides output with objects sorted by 'object_id' as follows:

 Array(7) :[ ​ 0: Object { key: "114", value: (11) […] } ​ 1: Object { key: "115", value: (10) […] } ​ 2: Object { key: "116", value: (5) […] } ​ 3: Object { key: "117", value: (15) […] } ​ 4: Object { key: "118", value: (13) […] } ​ 5: Object { key: "119", value: (12) […] } ​ 6: Object { key: "120", value: (10) […] } ]

Now, I face a challenge where objects within the arrays share the same 'assembly_id' and need to filter these objects based on 'item_id' and 'interval'. My goal is to refine the filtering process to achieve an output structured like:

Array :[
​
0: Object { objectIdKey: "114", value [assemblyIdKey: 2, value: [object...], assemblyIdKey: 3, value. [object...] }
​
1: Object { objectIdKey: "115", value: [assemblyIdKey: 5, value: [object...], assemblyIdKey: 4, value. [object...] }
​
​
2: Object { key: "objectIdKey", value: [assemblyIdKey: 6, value: [object...], assemblyIdKey: 7, value. [object...] }
]

Any tips, advice, or clues on how to improve this process are greatly appreciated. Thank you!

Cheers

Upon attempting to apply the transformArray function at a second level, it generates separate arrays for each object_id instead of achieving the desired outcome. Further refinement is needed.

Answer №1

It seems like your goal is to recursively apply grouping to the arrays that are generated, am I correct? So if you initially group by objectIdKey, then you would proceed to iterate through each group and further group it based on the next property.

Let me illustrate this with an example:

const data = [
{id: 1, id1: 'a', id2: 1},
{id: 1, id1: 'a', id2: 1},
{id: 1, id1: 'b', id2: 1},
{id: 1, id1: 'b', id2: 1},
{id: 1, id1: 'b', id2: 2},
{id: 1, id1: 'b', id2: 2},
{id: 2, id1: 'a', id2: 1},
]

const groupBy = (array, prop) => array.reduce( (grouped, element) => ({...grouped, [element[prop]]: [...(grouped[element[prop]] || []), element] }),{})
const groupByRecursively = (array, [prop, ...rest]) => !prop ? array : Object.entries(groupBy(array, prop)).map( ([key, value]) => ({[prop]: key, values: groupByRecursively(value, rest)}))
const result = groupByRecursively(data, ['id', 'id1', 'id2'])

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

Tips for recognizing users in socket.io?

I'm currently developing a chat application with socket.io. However, one issue I am facing is identifying the sender of a message. Unlike in Express where we have the "req" (request) variable to easily identify users, socket.io does not provide such f ...

Use AngularJS to take tab delimited text copied and pasted into a textarea, and then convert it into a table

One of the features in my app requires users to copy and paste tab delimited text. I need to convert this text into a table where each new column is represented by a tab and each new row is indicated by a new line. I've managed to create a list for e ...

Error encountered when trying to access JSON data from a .txt file due to

There are 3 text files (file1.txt, file2.txt, file3.txt) containing JSON formatted data. The size of the files is as follows: file1 = 104.55 Mb file2 = 104.68 Mb file3 = 104.49 Mb I can access and read file1 and file3 without any issues. However, when at ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

unusual behavior of UTF-8 characters in Blogger when utilizing JavaScript

I'm facing a peculiar issue with JavaScript in my Blogger code when dealing with certain characters like '¡' and '?'. For instance, the following code snippet displays ñéúüëò¡!¿? inside the div but shows ñéúüëò&# ...

Utilizing React to Extract the Value Following a Colon in the Document Object Model

Wanting to create a test for verifying the presence of text following a specific value in my HTML file: <span>Dog facts: something</span> The goal is to confirm that there is text after the phrase "Dog facts:" and it is not null. It's im ...

How to access global variables in node.js modules?

I'm looking to move some functionality to a new file called helpers.js. Below is the code that I have put in this file. How can I access the app variable within my method so that I can retrieve the config element called Path? Helpers = { fs: requ ...

the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with. The component in question contains the following select statement: this.store.select(getI ...

What is the name attribute of an ES2015 function?

var individual = { announceIdentity() { console.log(this.identity); }, get firstID() { return "Superman"; } }; individual.announceIdentity.identification // "identity" individual.firstID.identifier // "get firstID" I recently came acros ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

How can I send two responses in a single POST request using node.js?

Below is my router setup for handling responses: questionRouter.post('/questionsReply', (req, res) => { twilioResp(req, res); var newResponse = new Response(req.body); newResponse.save((err, data) => { if (err) return handleDBError(er ...

Exploring the depths of cURL and PHP beyond the basics

After realizing that my previous question was not quite right, I am back with a more accurate one. This time, I am working with cURL in PHP and trying to access a website. However, every time I change the site, the browser sends a value x to the server. If ...

Exploring Objects within an array using Angular loops

Hey there, I'm currently working on an Angular project and I need to retrieve the userName of the user for each comment that is posted. These entities are coming from my Spring Boot project. Is there a way to access the username for every comment? He ...

Different types of outputs that are suitable for a callback

I am currently developing a small node.js project focused on retrieving search terms from a Twitter feed. Although the search functionality is in place, I am facing difficulties in displaying this data on my webpage. The information I wish to showcase is s ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Issue with handlebars template

Below is a handlebars-template that I have: <script id="pins-list-template" type="text/x-handlebars-template"> {{#if ListCount > 0}} <ul> {{#each ListData}} <li> <img src="assets ...

The input field is failing to capture the final character entered

Is there a way to store all input files in a single object and use the information in a graph? Currently, when I enter the first character, it creates an empty object, so the last character I enter is not captured in the object. Any suggestions on how to ...

Transferring data using Jackson-2.9.7: JSON import/export operations

Greetings, Currently, I am engaged in a project that involves allowing the user to import/export program data into a JSON file. The data is of type TreeMap<String, List<Observation>>, where Observation is a class containing LocalDate date and ...