Generate a 2D matrix to represent a grid

I have a list of numbers that I need to convert into a two-dimensional array. For example:

let data=['1','4','2','1','6','9','1','5',]

The desired output would be:

result = [['1','4','2','1'],['6','9','1','5']]

My ultimate goal is to create a dynamic grid-style menu system in Ionic using the following example:

<div class="text-center" ng-init="models = [['12','1','2','3','3'],['4','4','5','6','7']]">
    <div ng-repeat="m in models">
        <span class="control-label1" ng-repeat="movie in m track by $index">
    {{movie}}</span>
        </div>
    </div>

To achieve this, I need to populate my array with unique values like so:

// Function to add a unique value to the array
$scope.addhourinArray = function (value) {

    if (value) {
        if ($scope.hourArray.indexOf(value) == -1) {
            $scope.hourArray.push(value);
        }
    }
};

// Adding values to the two-dimensional array
for (var i = 0; i < data.length; i++) {
    $scope.addhourinArray(hour);
}

Answer №1

I'm not entirely sure what you mean by the "Angular Way" in this particular situation, especially since creating a 2 dimensional array from a 1 dimensional one doesn't appear to be an Angular-specific issue.

Additionally, the dynamic nature of the data feeding into the menu is somewhat unclear (given that your example simply retrieves it from an ng-init). Assuming the data is sourced asynchronously, the following assumptions are made:

  • Typically, asynchronous sources are encapsulated within an Angular service. Any data transformation logic would usually reside within the service, unless the transformation is specific to the controller and the service provides alternate data representations to other parts of the application.
  • Consider encapsulating your menu into a directive that has its own template and controller.
  • Avoid using $scope unless necessary. The "Controller As" syntax was introduced in Angular JS 1.1.5 and has been steadily improving since then.

The code snippet below attempts to illustrate these concepts:

<!DOCTYPE html>
<html>
<head>
  <title>angular 1.x directive for movie-menu custom element</title>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
</head>
<body> 
  <div ng-app="myApp">
    <script type="text/ng-template" id="movie-menu.html">
      <div ng-repeat="m in mmvm.models">
        <span ng-repeat="movie in m track by $index">
          {{movie}}
        </span>
      </div>
    </script>

    <movie-menu></movie-menu> 
  </div>  
  <script type="text/javascript">
    (function () {

      dataServiceFactory.$inject = ['$q']; 
      function dataServiceFactory ($q) {

        function transformData (items) {
          var rowLength = ((items.length % 2) == 0 ? items.length : items.length - 1)/2,
          top = items.slice(0, rowLength), 
          bottom = items.slice(rowLength, rowLength + rowLength); 

          return [top, bottom];
        }

        function fakeData() {      
          var data, transformed, resultP, resolveResult, rejectResult;

          data = ['12','1','2','3','3','4','4','5','6','7','x'];

          transformed = transformData(data);

          resultP = $q(function(resolve, reject) {
            resolveResult = resolve;
            rejectResult = reject;        
          });

          resolveResult(transformed);

          return resultP; 
        }

        return { 
          getData: fakeData 
        }; 

      } 

      MovieMenuCtrl.$inject = ['dataService'];
      function MovieMenuCtrl (dataService) {
        var vm;

        function setModels (result) {
          vm.models = result;
        }

        vm = this;
        dataService.getData().then(setModels);    
      }

      movieMenuDdoFactory.$inject = [];
      function movieMenuDdoFactory () {
        return {
          restrict: 'E',
          scope: {},
          replace: true,
          templateUrl: 'movie-menu.html',
          controller: 'MovieMenuCtrl',
          controllerAs: 'mmvm',
          bindToController: true
        };
      }

      angular
        .module('myApp', [])
        .factory('dataService', dataServiceFactory)
        .controller('MovieMenuCtrl', MovieMenuCtrl)
        .directive('movieMenu', movieMenuDdoFactory);

    })();
  </script>     
</body>
</html>

References:
Chapter 1: Building a simple element directive - JSFiddle
How I've Improved My Angular Apps by Banning ng-controller
Refactoring Angular Apps to Component Style
AngularJS: Developer Guide: Dependency Injection - $inject Property Annotation
AngularJS: API: $q - $q constructor
Array.prototype.slice() - JavaScript | MDN

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

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

Trouble with Swiper carousel loading new slides

Currently, I am working on a project using Cordova and jQuery. I have implemented the Swiper library by idangero for handling slides. The problem arises when I add new slides and try to display them. Here is the relevant jQuery code snippet: if(row.pict ...

The aoColumns functionality in datatables seems to be malfunctioning

Attached is the application picture, where the column ORDER ID is not showing and instead a PLUS sign is displayed. This causes all columns to shift one position to the right. ajax Every time I run the application, it displays the following error message: ...

The function in which the "useStyles" React Hook is invoked is not a valid React function component or a defined custom React Hook function

After integrating Material UI with React, I encountered the following error message: React Hook "useStyles" is called in function "appBar" which is neither a React function component nor a custom React Hook function I have carefully checked the rules of ...

React: Remember to always retain the initial four characters when making changes

I have implemented an input component for phone numbers using the react native phone input library, which automatically adds the international code. However, I am facing an issue where the international code +234 is deleted when the user presses the back b ...

JS function to reverse a string

Not to worry, I've managed to figure out how to reverse a string (a one-word string at least). > function reverse(s){ > return s.split("").reverse().join(""); } Is there a way to reverse a string in this manner: "Dady come home" -> "yd ...

When do Angular.js memory leaks become a cause for concern?

My application is quite large, built on angular with nested states, directives, and data tables. We recently decided to switch to a full single-page setup, which raised some performance concerns. While Chrome seems unaffected visually, Firefox appears to s ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...

Creating a hover effect for a specific card while maintaining the rest of the cards unaffected

When hovering over a card, all icons are displayed instead of just the icons for that specific card. I want to show only the icons for the card being hovered on (example output: image). The cards are generated automatically using v-for and fetching data fr ...

Can I assign a custom form id before manually triggering submission using AJAX?

I have developed an interesting code snippet that uses AJAX to submit a form only if the form has an ID attached to it. $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id& ...

Is there a way to update a variable in a controller using AJAX?

Is it possible to update a variable in the controller using Ajax? Controller: $basl = array(2018,11,18,0,0); $deger = 3; $baslamatarihi=Carbon::create($basl[0],$basl[1],$basl[2],$basl[3],$basl[4]); $bitistarihi = Carbon::create($basl[0],$basl[1],$basl[2] ...

Scraping multiple websites using NodeJS

I have been immersing myself in learning NodeJS and experimenting with web scraping a fan wikia to extract character names and save them in a json file. I currently have an array of character names that I want to iterate through, visiting each URL in the a ...

Django Crispy Forms do not support JavaScript functionality

In my project, I am working on creating a client form where the country, province, and city are selected based on different models: class Country(models.Model): Country = models.CharField(max_length=100, unique=True) def __str__(self): ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

Creating a seamless navigation experience with Next.js: Implementing per-page layouts for efficient 2-link navigation on a single screen

In my next.js project, I have a URL like "http://localhost:3000/forum". If a user goes to "http://localhost:3000/forum/{postId}", I want to redirect them back to "http://localhost:3000/forum" My folder structure is in the 'App' directory and I h ...

AngularJS - Displaying the initial content in the <ui-view> container

Can default code be placed inside a <ui-view> element without any issues? It seems to work for me, but I can't find any definitive information on whether it's acceptable or not. Currently, I have set up the "default" view to display a list ...

Display an array in a table based on a specific condition using PHP

I am working with an array that looks like this: Array ( [2-3] => player1 [1-3] => player2 [2-0] => player1 [5-1] => player1 [2-4] => player2 [4-1] => player2 ) My goal is to display all the keys associated with the value "player1" in a ...