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

Authenticate the refresh token and access token by utilizing JWT

I find myself in a unique situation where I do not currently possess any database. However, I have created a simple server.js file through which I send my requests (by running server.js using node server.js). My goal is to add user-login functionality to m ...

How come I am receiving the E11000 error from Mongo when I have not designated any field as unique?

Encountering an issue while attempting to save the second document to MongoDB Atlas. The error message reads as follows: Error:MongoError: E11000 duplicate key error collection: test.orders index: orderId_1 dup key: { orderId: null } Despite having no un ...

Dragging items in the horizontal list of Knockout-Sortable causes them to be pushed vertically

For my application development using knockout.js, I am implementing knockout-sortable to create drag-and-drop sortable lists. The setup involves a vertical list with each item containing a horizontal list. While the vertical lists are functioning properly, ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

I am facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data: { "Stations": { "44": { "NAME": "Station 1", "BRANCH_CD": "3", "BRANCH": "Bay Branch" }, "137": { "NAME": "Station 2", ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Creating a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

Issue with setting state in useEffect causing an infinite loop due to either linter warning or user error

In its current state, my component appears as follows: const { listOfStuff = [{name:"john"},{name:"smith"}] } = props const [peopleNames, setPeopleNames] = useState([]) useEffect(() => { listOfStuff.forEach(userName => { setPeopleNames(people ...

JavaScript: A step-by-step guide to extracting the file name and content from a base64 encoded CSV

I have a base64 string that was generated by encoding a csv file, const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzd ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...