Tips for organizing data in an Angular table with a single row span for a specific property

Struggling to come up with a suitable title for this query.

The issue at hand: Imagine a table consisting of two columns - one for car brands and the other for car models. The desired layout is as follows:

as depicted in the image

In simpler terms, each brand name should only be displayed once.

The input array provided is in JSON format:

[{"brand":"Audi","model":"A1"}, 
{"brand":"Audi","model":"A2"}, 
{"brand":"Audi","model":"A3"}, 
{"brand":"BMW","model":"3 Series"}, 
{"brand":"BMW","model":"5 Series"}]

Unable to figure out how to achieve this using AngularJS.

Answer №1

Check out this solution to showcase the data with the groupBy filter in a creative way.

angular.module('app',['angular.filter'])
  .controller('MainController', function($scope) { 
    $scope.cars = [{
    "brand": "Audi",
    "model": "A1"
  }, {
    "brand": "Audi",
    "model": "A2"
  }, {
    "brand": "Audi",
    "model": "A3"
  }, {
    "brand": "BMW",
    "model": "3 Series"
  }, {
    "brand": "BMW",
    "model": "5 Series"
  }];
 });
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>

<div ng-app="app" ng-controller="MainController"> 
  <table>
    <tbody ng-repeat="(key, value) in cars | groupBy: 'brand'">
      <tr>
        <td rowspan="{{value.length}}">{{key}}</td>
        <td>{{value[0].model}}</td>
      </tr>
      <tr ng-repeat="car in value" ng-if="!$first">
        <td>{{car.model}}</td>
      </tr>    
    </tbody>
  </table>
</div>

Answer №2

angular.module('app',['angular.filter'])
  .controller('MainController', function($scope) { 
    $scope.cars = [{
    "brand": "Audi",
    "model": "A1"
  }, {
    "brand": "Audi",
    "model": "A2"
  }, {
    "brand": "Audi",
    "model": "A3"
  }, {
    "brand": "BMW",
    "model": "3 Series"
  }, {
    "brand": "BMW",
    "model": "5 Series"
  }];
 });
table {
    border-collapse: collapse;
}
table, th, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>

<div ng-app="app" ng-controller="MainController"> 
  <table>
    <thead>
      <tr>
        <th>Brand</th>
        <th>Model</th>
      </tr>
    </thead>
    <tbody ng-repeat="(key, value) in cars | groupBy: 'brand'">
      <tr>
        <td rowspan="{{value.length}}">{{key}}</td>
        <td>{{value[0].model}}</td>
      </tr>
      <tr ng-repeat="item in value" ng-if="!$first">
        <td>{{item.model}}</td>
      </tr>    
    </tbody>
  </table>
</div>

Answer №3

To group the data, you can use the following method.

var app = angular.module('exApp',[]);
app.controller('ctrl', function($scope){
var values = [{"brand":"Audi","model":"A1"}, 
{"brand":"Audi","model":"A2"}, 
{"brand":"Audi","model":"A3"}, 
{"brand":"BMW","model":"3 Series"}, 
{"brand":"BMW","model":"5 Series"}];

var datass = {};
for (var i = 0; i < values.length; i++) {
  var brandName = values[i].brand;
  if (!datass[brandName]) {
    datass[brandName] = [];
  }
  datass[brandName].push(values[i].model);
}
var mynewArray = [];
for (var brandName in datass) {
  mynewArray.push({brand: brandName, model: datass[brandName]});
}
$scope.newData = mynewArray;

//console.log(mynewArray);

// --or--
var group_to_values = values.reduce(function(obj,item){
    obj[item.brand] = obj[item.brand] || [];
    obj[item.brand].push(item.model);
    return obj;
}, {});

var groups = Object.keys(group_to_values).map(function(key){
    return {brand: key, model: group_to_values[key]};
});
//$scope.newData = groups;
//console.log(group_to_values);
//console.log(groups);

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>th,td,tr{border:1px solid}</style>
<body ng-app="exApp" ng-controller="ctrl">
<table>
<tr><th>car</th><th>model</th></tr>
<tr ng-repeat="new in newData">
<td>{{new.brand}}</td>
<td>
<table>
<tr ng-repeat="(key, value) in new.model track by $index"><td>{{value}}</td></tr></table>
</td>
</tr>
</table>
</body>

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

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

Transferring information through Ajax to PHP

When using AJAX to send a string via the GET method, I've noticed that punctuation characters sometimes don't appear when echoed in PHP. For instance, sending "sub + 12" results in PHP echoing "sub 12", and sending "&()*" echoes an empty str ...

Determine the frequency of occurrences in an array where two elements are less than or equal to a specified sum - Using JavaScript

I've been working on a JavaScript function that counts the number of times two elements add up to a given sum. However, now I'm looking to modify this so that it not only considers when the two elements equal the sum, but also when they are less ...

Ways to determine the presence of a value in an array

Here is an example array: [ {practitioner: "place_1509136116761", H0709: false, H0911: false, H1113: false, H1315: false}, {practitioner: "place_1509136116772", H0709: true, H0911: false, H1113: true, H1315: false}, {practitioner: "place_15091361166 ...

A step-by-step guide to implementing bubble sort for sorting a 2D array in JavaScript

Here's a function that requires modification to work with a 2D array: function sortTwoDimensionalArray(arr) { var numRows = arr.length; for (var i = 0; i < numRows; i++) { for (var j = 0; j < (numRows - i - 1); j++) { if(arr[j][ ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Automate the detection of a connected device via USB on a NodeJS server

I created a web interface for a colorimeter by using a NodeJS server that can read USB serial inputs through the serialport npm library. This information is then sent to a local web page. The colorimeter consists of a circuit with a microcontroller that is ...

Difficulty in finding and retrieving array indexes that match a specific character pattern

Is it possible to return indexes from an array based on a search term, regardless of the order of characters in the array? const array = ['hell on here', '12345', '77788', 'how are you llo']; function findMatchingI ...

Prevent the user from being redirected to the login page again after they have already logged in, even if they attempt to go back using the browser's back button

I am in the process of building a login page that checks certain conditions and redirects the user to the home page. However, I want to implement a feature where once the user has visited the home page, they cannot go back to the login page by clicking the ...

Executing a keystroke in Selenium Webdriver using JavaScript

I've been writing a test using Selenium WebDriverJS, and now I need to simulate pressing a key on the keyboard. Is it possible to do this with Selenium WebDriverJS? If so, how can it be done? In Java, we achieve this as follows: driver.findElement(Lo ...

using a comparison array as a parameter for the filter method in JavaScript

How can I filter out values from an array using another array as a reference in the filter function? x = [3,4,5]; y = [4,5]; var result = x.filter(customFilter); function customFilter(element, index, array){ // code here }); What is the most effect ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

The ng-repeat directive doesn't render any content on the page

Check out this code snippet HTML <div ng-controller="moveController as vm"> <div ng-repeat="move in vm.moves"> Move of the Week: <br /> {{move}} </div> JavaScript function retrieveMovesForCurrentWeek() { service.f ...

Neglecting to Execute Success Function After Retrieving Data from PageMethods Using Multiple Parameters in C#

I attempted to trigger my OnSuccess function, but it did not execute on the server. This is my code: function Get_Data(option , text){ //returns 'data', 'data', --not call OnSuccess-- PageMethods.BindSeries(option,text,OnSuccess); ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP c ...

What is the best way to clear a MongoDB objectId field, set it to null, or ultimately remove it from a

Custom Modal Schema : { "title":{type:String,required:true}, "genre":{type:mongoose.Schema.Types.ObjectId,ref:"Genre"} } Upon creating a document using this schema, the document structure appears as follows: { "_id":ObjectId("5abcde12345fgh6789ijk ...

The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below: [ { "lat": 53.1522756706757, "lon": -0.487157731632087, "size": 63, "field": "TestField", ...

Conceal the "Load More" button on the filter tabs, with the exception of the "

My website features filterable tabs and photos categorized into different groups. The main category is "All" followed by 4 additional categories. There are two important functions that I have implemented: The first function is for filtering: $(function( ...

angular $stateprovider malfunctioning and causing unexpected behavior

Currently, I am utilizing angular's $stateProvider to enable routing within my application. The main HTML file is index.html and I am updating the HTML content inside it with the following code... app.config(function($stateProvider, $urlRouterProvide ...