Organizing with dynamic attributes within angularJS

I have been working on creating a spreadsheet using Angular, and I have managed to implement most of the basic features. However, I am facing a challenge with sorting data by a single column within my current data structure.

Here is the link to the Plnkr showcasing my work so far.

Do you believe that restructuring the data to have separate arrays for different columns would be a better approach, or is there a way to achieve sorting within the existing structure?

At the moment, the spreadsheet is dynamically generating properties for the scope object based on cell value changes.

Below is the code snippet responsible for generating and calculating cell values:

 process = function (exp) {
        return exp.replace(/[A-Z]\d+/g, function (ref) {
            return 'result("' + ref + '")';
        })
    }

    $scope.result = function (cell) {
        if ($scope.cells[cell]) {
            if (stringStartsWith($scope.cells[cell], "=")) {
                var val = $scope.cells[cell].substring(1);
                return $parse(process(val))($scope);
            }
            else {
                return $scope.cells[cell];
            }
        }
        else {
            return $scope.cells[cell];
        }
    };

Answer №1

For those looking for an array (multi-)sorting utility, you may find this tool useful here (use as necessary)

Here is the source code:

    // Utility for sorting arrays with multiple (nested) fields 
    // enabling independent ascending or descending sorting for each field
    // Source: https://github.com/foo123/sinful.js
    [Array, 'sorter', function () {

        var arr = this, i, args = arguments, l = args.length,
            a, b, avar, bvar, variables, step, lt, gt,
            field, filter_args, sorter_args, desc, dir, sorter,
            ASC = '|^', DESC = '|v';
        
        if ( l )
        {
            step = 1;
            sorter = [];
            variables = [];
            sorter_args = [];
            filter_args = []; 
            for (i=l-1; i>=0; i--)
            {
                field = args[i];
                filter_args.unshift('f'+i);
                if ( field.push )
                {
                    sorter_args.unshift(field[1]);
                    field = field[0];
                }
                else
                {
                    sorter_args.unshift(null);
                }
                dir = field.slice(-2);
                if ( DESC === dir ) 
                {
                    desc = true;
                    field = field.slice(0,-2);
                }
                else if ( ASC === dir )
                {
                    desc = false;
                    field = field.slice(0,-2);
                }
                else
                {
                    desc = false;
                }
                field = field.length ? '["' + field.split('.').join('"]["') + '"]' : '';
                a = "a"+field; b = "b"+field;
                if ( sorter_args[0] ) 
                {
                    a = filter_args[0] + '(' + a + ')';
                    b = filter_args[0] + '(' + b + ')';
                }
                avar = 'a_'+i; bvar = 'b_'+i;
                variables.unshift(''+avar+'='+a+','+bvar+'='+b+'');
                lt = desc ?(''+step):('-'+step); gt = desc ?('-'+step):(''+step);
                sorter.unshift("("+avar+" < "+bvar+" ? "+lt+" : ("+avar+" > "+bvar+" ? "+gt+" : 0))");
                step <<= 1;
            }
            return (new Function(
                    filter_args.join(','), 
                    ['return function(a,b) {',
                     '  var '+variables.join(',')+';',
                     '  return '+sorter.join('+')+';',
                     '};'].join("\n")
                    ))
                    .apply(null, sorter_args);
        }
        else
        {
            a = "a"; b = "b"; lt = '-1'; gt = '1';
            sorter = ""+a+" < "+b+" ? "+lt+" : ("+a+" > "+b+" ? "+gt+" : 0)";
            return new Function("a,b", 'return '+sorter+';');
        }
    }],

Here are some test examples:

var arr = [
    {f1: 1, f2: {f3: 3} },
    {f1: 1, f2: {f3: -4} },
    {f1: -1, f2: {f3: 2} }
];
var multiSorter = Array.sorter('f1|^','f2.f3|v');
var multiSorterFilter = Array.sorter('f1|^',['f2.f3|v', function(f){return -f;}]);

require('assert').deepEqual(arr.sort(multiSorter), [{f1: -1, f2: {f3: 2} },{f1: 1, f2: {f3: 3} },{f1: 1, f2: {f3: -4}}]);
require('assert').deepEqual(arr.sort(multiSorterFilter), [{f1: -1, f2: {f3: 2} },{f1: 1, f2: {f3: -4} },{f1: 1, f2: {f3: 3}}]);

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

Refreshing the MarkerCluster following an AJAX request

My current challenge involves an AJAX function that retrieves posts based on users with a specific role. While the query itself works fine, I am encountering an issue with refreshing the markers on Google Maps after the AJAX request is complete and the pos ...

What is the best way to initiate WebXR from an iframe in a Next.js environment?

I am currently working on a Next.js app: https://codesandbox.io/s/next-js-forked-6fgnr7?file=/index.tsx I have implemented the functionality for it to open WebXR on Android Chrome when clicking on the AR button located at the bottom left ("in AR betracht ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Request with content Type multipart/form experienced Error 406

I encountered an issue with my axios request in Express const formData = new FormData(); formData.append("file", fs.createReadStream(file.path)); formData.append("requestid", '123456'); const options = { method: 'POST& ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

How to choose an option from a dropdown menu using React

In a React application, I am creating a straightforward autocomplete feature. The code is outlined below. index.js import React from 'react'; import { render } from 'react-dom'; import Autocomplete from './Autocomplete'; co ...

Encountering an issue where the Angular build is unable to locate the installed Font-Awesome node module

Every time I attempt to compile my project using ng build --prod, I encounter the following error: ERROR in ./src/styles.scss Module build failed: ModuleBuildError: Module build failed: Error: Can't resolve '~font-awesome/css/font-awesom ...

Viewing information from the database without the need to refresh the page

HTML <textarea>Enter your question here</textarea><button class="askButton">SUBMIT</button> Upon clicking the button, the question is stored in the database using Ajax, jQuery, and Laravel. However, the question only appears after ...

C program that will output all the elements contained in each structure within an array of structures

I've been working on a function in C that is supposed to take an array of structs, each holding employee information, and then print out all the details for each struct. However, I'm not getting any output from my code. Can anyone help me trouble ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Tips for providing arguments in the command line to execute a yarn script

Just starting out with JavaScript. I understand that npm allows for passing variables in the command line using process.env.npm_config_key like this: npm run --key="My Secret Passphrase" test:integration How can I achieve the same thing with yarn? I&apo ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

Optimizing the display of multiple list items using Javascript for two separate UL elements on a single webpage

How can I display a maximum of 5 list items in two separate UL elements on the same page and hide the rest? Users should be able to see more items by clicking a dynamic "See more" element created by JavaScript. Below are the UL elements I want to work wit ...

Could the issue with jQuery selector potentially be connected to AngularJS?

Integrating a third-party web page into an Android webview in our app presents the challenge of automating the login process. Since the app has access to the login credentials for the third-party site, I'd like to execute some Javascript for this purp ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Interacting with objects in a loaded OBJ model using ThreeJS

I have an obj model representing a map with tree objects. After successfully loading the model, I am trying to access one specific tree object named Tree1. How can I achieve this? Currently, my code looks like this: loader.load( 'map.obj', fun ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

"Enhance your gaming experience with Three JS special effects

I'm in the process of creating a multiplayer web game using Three JS. So far, I have successfully implemented the game logic on both client and server sides, mesh imports, animations, skill bars, health bars, and the ability for players to engage in c ...