Changing the array of objects: various operations on arrays and objects

Array of Data

[
 {group: 'a', tab: "1", name: 'input1'},
 {group: 'b', tab: "1", name: 'input2'},
 {group: 'b', tab: "1", name: 'input3'},
 {group: 'c', tab: "2", name: 'input4'},
 {group: 'a', tab: "1", name: 'input5'},
 {group: 'c', tab: "2", name: 'input6'},
];

In my application, each element in the array (totaling over 50) represents an input that is part of a specific group (a, b, or c) and tab (1, 2, etc.). To achieve my goal, I aim to determine how many groups are associated with each tab by creating an object or array with this structure:

 [
      {tab1:{groups: ["a", "b"]}},
      {tab2:{groups: ["c"]}},
    ]

Answer №1

To create a distinct array and manipulate each item, we can utilize the Set method for uniqueness, map function to modify items, and filter to eliminate elements from the array. Here is how I achieved it:

  1. Generate a unique tab list.
  2. Transform the list to generate a new object for each tab
    1. Apply filter to identify tabs of a specific type
    2. Map that filtered result to extract only the group letter
    3. Create another set for a unique group letter list.
  3. Finally, the revised object is fed back to the initial map item to produce an array of items.

This implementation appears as shown below:

let data = [
 {group: 'a', tab: "1", name: 'input1'},
 {group: 'b', tab: "1", name: 'input2'},
 {group: 'b', tab: "1", name: 'input3'},
 {group: 'c', tab: "2", name: 'input4'},
 {group: 'a', tab: "1", name: 'input5'},
 {group: 'c', tab: "2", name: 'input6'},
];

let tabs = [...new Set(data.map(itm => itm.tab))].map(tab => {
  return {
    ['tab' + tab]: {groups: [...new Set(data.filter(i => i.tab == tab).map(i => i.group))] }
  }
});

console.log(tabs);

Answer №2

Utilize the power of Array.reduce() to efficiently create a map and group it based on Tab values, then extract the desired result using Object.values().

let arr = [
    {group: "a", tab: "1", name: "input1"},
    {group: "b", tab: "1", name: "input2"},
    {group: "b", tab: "1", name: "input3"},
    {group: "c", tab: "2", name: "input4"},
    {group: "a", tab: "1", name: "input5"},
    {group: "c", tab: "2", name: "input6"}
];

let result = Object.values(arr.reduce((a, {group, tab})=>{
  a[tab] = a[tab] || {["tab"+tab] : {group : []}};
  if(!a[tab]["tab"+tab].group.includes(group))
    a[tab]["tab"+tab].group.push(group);
  return a;
},{}));

console.log(result);

:

Answer №3

One effective approach is to utilize a Map for grouping and a Set for storing unique values.

const data = [{ group: 'a', tab: '1', name: 'input1' }, { group: 'b', tab: '1', name: 'input2' }, { group: 'b', tab: '1', name: 'input3' }, { group: 'c', tab: '2', name: 'input4' }, { group: 'a', tab: '1', name: 'input5' }, { group: 'c', tab: '2', name: 'input6' }];
const result = Array.from(
    data.reduce(
        (m, { tab, group }) => m.set(tab, (m.get(tab) || new Set).add(group)),
        new Map
    ),
    ([tab, groups]) => ({ ['tab' + tab]: { groups: Array.from(groups) } })
);

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

Answer №4

Give this code a try

const data = [
  { group: "x", tab: "1", name: "item1" },
  { group: "y", tab: "1", name: "item2" },
  { group: "y", tab: "1", name: "item3" },
  { group: "z", tab: "2", name: "item4" },
  { group: "x", tab: "1", name: "item5" },
  { group: "z", tab: "2", name: "item6" },
];

const modify = (data) => {
  const result = [];
  Object.keys(data).forEach((element) => {
    const ref = `tab${data[element].tab}`;
    
    if (typeof (result[ref]) === 'undefined') {
      result[ref] = { groups: [] };
    }
  
    if (!result[ref].groups.includes(data[element].group)) {
      result[ref].groups.push(data[element].group);
    }
  });
  return result;
};

console.log(modify(data));

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

Add some flair to your list by animating the text within it

My goal is to add animation to the text within the list. Below is the code snippet: <div id="about" class="row section"> <div class="col-sm-8"> <h2 style="color:black;">About me!</h2> <ul> <li > ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Saving an Axios request array to a Laravel controller in Laravel using VueJs

I am working on a laravel 5.7 application that utilizes VueJS 2.0 for the front end. The issue I am facing involves two tables with a many-to-many relationship: 'commandes' and 'produits'. When trying to pass data into my 'commande ...

Ways to display a variable prior to making an axios request

I have a get request that saves the result in a variable named name_student. How can I access this variable in other methods? Or how should I declare it? Here is the code snippet: getStudent(){ axios.get('https://backunizoom.herokuapp.com/student/2 ...

loop failing to refresh element within array

Is there a way to update a specific property in every element of an array to match its index? I attempted the following approach: static reindexComponentsOnMultiplePages(components) { return components.forEach((el, idx) => (el.componentIndex = id ...

Is dividing a website into two parts acceptable?

In the process of creating a social network, one major concern is making sure that the content is easily readable by Google while also providing users with a seamless and engaging experience through Ajax support. However, it's well-known that Ajax and ...

Integrating Dart with external libraries

Here is a straightforward example demonstrating the usage of a map library: <!doctype html> <html> <head> <script src="http://api4.mapy.cz/loader.js"></script> <script>Loader.load()</script> </head; &l ...

Tips for transferring complete HTML content within a JSON payload

I've been working on a jQuery script to convert an entire HTML page into JSON text. My goal now is to transform this code into a JSON string. In the resulting JSON: The 'text1' value will store the complete HTML in a single string format ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

Exploring AngularJS unit testing: integrating async and await with Jasmine

I'm currently facing a challenge with unit testing my Angular service using the async/await keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise is functioning correctly, however, I am encountering difficulties in g ...

Are your divs getting truncated?

Currently faced with a perplexing issue where inserting elements into a div causes scaling problems, resulting in most of the divs being cut off. This glitch occurs when two new elements are added. Despite changing page sizes and thoroughly debugging by o ...

Why does the address bar show value changes in IE when using window.location.hash, but the value doesn't change in the DOM when going

Here is a sample JavaScript code that attempts to detect the back button event: document.location.hash="#1"; document.location.hash="#2"; document.location.hash="#3"; function check() { if("#3"!=window.location.hash) { alert("Back button clic ...

The Vue.js development server compiler is hitting a roadblock at 49% progress

My Vue JS project keeps getting stuck at 49% or sometimes 62% when I run npm run serve. No matter how long I wait, it never seems to move past that point. I have searched online many times for a solution to this issue, but it appears that no one else is e ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...

Encountering difficulties accessing functions from apollo-server-express

I have been following a tutorial and attempting to launch the node server, but I am unable to import these functions from the Apollo package const {graphqlExpress, graphiqlExpress} = require('apollo-server-express'); // importing functions here ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Updating an object with AngularJS

Let's consider the code snippet below: var absenceType = {name: 'hello'}; this.newAbsenceType = angular.copy(absenceType); After making changes to this.newAbsenceType, you want to apply these changes to the original object. I have explore ...

Calculating the total length of an SVG element using React

Looking to animate an SVG path using React (similar to how it's done in traditional JavaScript: https://css-tricks.com/svg-line-animation-works/), but struggling when the path is created using JSX. How can I find the total length of the path in this s ...

Remove all $.ajax requests from content that has been loaded using $.ajax in jQuery

I'm currently working on a page where users can click a link to load content using $.ajax into a designated container div. However, I've encountered an issue with multiple clicks causing an increase in the number of $.ajax requests and resulting ...