What is the best way to adjust and filter an array based on a single value?

Here is an array that needs to be modified:

[
  {name: "test", value: "test", group: 0},
  {name: "test1", value: "test2", group: 0},
  {name: "test3", value: "test3", group: 1},
  {name: "test4", value: "test4", group: 1},
  {name: "test5", value: "test5", group: 1},
  {name: "test6", value: "tes6t", group: 2},
  {name: "test7", value: "test7", group: 2},
]

The desired outcome for this array is as follows:

[
  {name: "test", value: "test", group: 0, selections: [
    {name: "test", value: "test", group: 0},
    {name: "test1", value: "test1", group: 0}
  ]},
  {name: "test3", value: "test3", group: 1, selections: [
    {name: "test3", value: "test3", group: 1},
    {name: "test4", value: "test4", group: 1},
    {name: "test5", value: "test5", group: 1}
  ]},
  {name: "test6", value: "tes6t", group: 2, selections: [
    {name: "test6", value: "tes6t", group: 2},
    {name: "test7", value: "test7", group: 2}
  ]},
]

To achieve this without using multiple for loops in JavaScript/TypeScript, filtering for items based on their group value and adding them to the first element's selections array can be done efficiently.

What would be the best approach to accomplish this task effectively?

Answer №1

To achieve this, one can utilize the power of Array.prototype.reduce.

const data = [
  {name: "example1", value: "example1", group: 0},
  {name: "example2", value: "example2", group: 0},
  {name: "example3", value: "example3", group: 1},
  {name: "example4", value: "example4", group: 1},
  {name: "example5", value: "example5", group: 1},
  {name: "example6", value: "example6", group: 2},
  {name: "example7", value: "example7", group: 2},
];

const groupedData = data.reduce((result, current) => {
  result[current.group] ? result[current.group].items.push(current) : result[current.group] = {
    ...current,
    items: [current]
  };
  return result;
}, {});
const finalOutput = Object.values(groupedData);
console.log(finalOutput);

Answer №2

Utilizing Array.prototype.reduce once again showcases its effectiveness in handling such tasks ...

function collectItemByGroupAndSelection(collector, groupItem) {
  const { index, list } = collector;
  const { group: groupKey } = groupItem;

  let selectionGroup = index[groupKey];
  if (!selectionGroup) {

    selectionGroup = index[groupKey] = {
      ...groupItem,
      selections: [],
    };
    list.push(selectionGroup);
  }
  selectionGroup.selections.push({ ...groupItem });
  
  return collector;
}

const sampleData = [
  {name: "test", value: "test", group: 0},
  {name: "test1", value: "test2", group: 0},
  {name: "test3", value: "test3", group: 1},
  {name: "test4", value: "test4", group: 1},
  {name: "test5", value: "test5", group: 1},
  {name: "test6", value: "tes6t", group: 2},
  {name: "test7", value: "test7", group: 2},
];

console.log(
  "displaying array result directly through the collector's `list` property ...",
  sampleData.reduce(collectItemByGroupAndSelection, {

    index: {},
    list: [],

  }).list
);

console.log(
  "showcasing the content of the collector's `index` object ...",
  sampleData.reduce(collectItemByGroupAndSelection, {

    index: {},
    list: [],

  }).index
);

// The following example is unnecessary since the method
// utilized within one iteration already constructs both data
// structures - an object and an array ...

console.log(
  "processing the `index` object using `Object.values` ...",
  Object.values(
    sampleData.reduce(collectItemByGroupAndSelection, {

      index: {},
      list: [],

    }).index
  )
);
.as-console-wrapper { min-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

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

I'm experiencing an issue where my drum app element does not refresh after performing an action dispatch

Struggling with my React/Redux drum app, I'm at a roadblock with the final component that should update with the selected object's ID through an action dispatch. It baffles me why the element won't reflect the changes even though I've c ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

Issue with Vue template not displaying within a loop

After completing a basic Vue tutorial on setting up a Todo app, I decided to integrate some aspects of it into a website I am developing. However, I have encountered an issue with my for-loop that is not functioning as expected. The project was initially ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

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 = () => { ...

Is there a problem with Angular2 using TypeScript?

Currently, I am in the process of setting up my machine for Angular development by following the guidelines provided on https://angular.io/docs/ts/latest/quickstart.html As I proceeded to run "npm start" to launch my site, I encountered an issue with the ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

Manipulating selected values in VueJs v-select using methods

I am currently working on achieving the following goal: When I select the option "Alle openstaande" (result_id = 0), I want to select all these result_ids: [-1,-2,-3,-5,-7,-8,-11,-12] and deselect result_id 0. The variable mergedResults stores an array o ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

What steps can be taken to ensure that an ObjectID does not transition into a primitive form

Is there a way to avoid an ObjectID from being converted into a primitive data type when transferring in and out of Redis? Would converting it to a JSON string be a possible solution? Thanks! ...

Guidance that utilizes the scope of a specific instance

I have successfully created a d3.js directive, but I am facing an issue when resizing the window. The values of my first directive seem to be taking on the values of my second directive. How can I separate the two in order to resize them correctly? (both ...

The for loop does not cycle through every element

I'm working on a class project that involves creating custom HTML tags with JavaScript. I have a for loop set up to iterate over each use of the tag, but for some reason, it only seems to loop over every other tag. I'm specifically trying to crea ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...