logo
down
shadow

Grouping javascript array items based on their properties with AngularJS


Grouping javascript array items based on their properties with AngularJS

By : Nadeem Khan
Date : November 21 2020, 04:01 AM
like below fixes the issue Imagine having a list of wines: , Just use search filter :
code :
 <b>Pick your category: (Hard coding)</b>
            <ul>
              <li style="cursor:pointer" ng-click="click_filter('red')">red</li>
              <li style="cursor:pointer" ng-click="click_filter('merlot')">merlot</li>
              <li style="cursor:pointer" ng-click="click_filter('white')">white</li>
              <li style="cursor:pointer" ng-click="click_filter('chardonnay')">chardonnay</li>
            </ul>

    <b>Result</b>
          <div ng-repeat="wine in wines | filter:search ">
          <b>{{wine.name}}</b> - (category): {{wine.category}}
          </div>
    </div>
 $scope.click_filter = function(item) {
         $scope.search = item;
     }


Share : facebook icon twitter icon
Grouping items upto two levels based on values using javascript

Grouping items upto two levels based on values using javascript


By : KIM
Date : March 29 2020, 07:55 AM
it should still fix some issue I see 2 possible ways of solving this:
1: Pass the data once and organize it in multidimensional object and the loop over it to output the result.
code :
sO = [
        {
            "classification": "books",
            "category": "comics",
            "Code": "ITBCBAT08",
            "Title": "Dark Knight"
        },
        {
            "classification": "cds",
            "category": "comics",
            "Code": "ITCCCSUP02",
            "Title": "Superman"
        },
        {
            "classification": "books",
            "category": "literature",
            "Code": "ITBLII01",
            "Title": "To Kill a Mockingbird"
        }
    ];

     // Result = $.parseJSON(sO);
     Result = sO;

var html = "", data = {}, cls, cat;

for(var i in sO) {
    cls = sO[i].classification;
    cat = sO[i].category;

    if(typeof data[cls] === "undefined") {
        data[cls] = [];
    }

    if(typeof data[cls][cat] === "undefined") {
        data[cls][cat] = [];
    }

    data[cls][cat].push(sO[i]);
}

for(var cls in data) {
    html += "<div class=\"main\" style='display:block' >";
    html += "<h2>" + cls  + "</h2>";

    for(var cat in data[cls]) {
        html += "<h3>" + cat  + "</h3>"

        for(var item in data[cls][cat]) {
            html += "<p>" + data[cls][cat][item].Title + "</p>";   
        }
    }

    html += "</div>";
    html += "<div class=\"clr\"></div>";
}
$('#test').append(html);
Grouping Array Items Based on Common String

Grouping Array Items Based on Common String


By : user5250497
Date : March 29 2020, 07:55 AM
Hope this helps I would build an array that maps role names to an array of people who filled that role. Possibly something like this:
code :
$roles = array();
for($i = 0; $i < $arrayrole1; $i++) {
    $names = explode(", ", $arrayname[$i]);
    $name = $names[1] . " " . $names[0];
    // append the name to the array of people filling the role
    $roles[$arrayrole[$i]][] = $name; 
}

// print out the list of people in each role
foreach($roles as $rolename => $people) {
    echo $rolename . ": " . implode(", ", $people) . "<br />";
}
grouping of similar array items under a parent based on a condition javascript

grouping of similar array items under a parent based on a condition javascript


By : Richard Zhen
Date : March 29 2020, 07:55 AM
I hope this helps . , You need some grouping for it.
code :
var textTag = [{ text: "3", items: [{ name: 'item1.jpeg' }, { name: 'item2.jpeg' }, { name: 'item3.jpeg' }] }, { text: "2", items: [{ name: 'item1.gif' }, { name: 'item2.gif' }, { name: 'item3.png' }] }],
    grouped = textTag.map(function (a) {
        var o = {};
        a.items.forEach(function (b) {
            var n = b.name.split('.');
            o[n[1]] = o[n[1]] || [];
            o[n[1]].push(n[0]);
        });
        return o;
    });

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
Grouping an Array and Counting items creating new array based on Groups

Grouping an Array and Counting items creating new array based on Groups


By : Роман Мисько
Date : March 29 2020, 07:55 AM
wish of those help With proper data, you could iterate the array of objects and count the regions.
code :
var dataResult = [{ region: "Africa", fruit: "Orange", user: "Gary" }, { region: "Africa", fruit: "Apple", user: "Steve" }, { region: "Europe", fruit: "Orange", user: "John" }, { region: "Europe", fruit: "Apple", user: "bob" }, { region: "Asia", fruit: "Orange", user: "Ian" }, { region: "Asia", fruit: "Apple", user: "Angelo" }, { region: "Africa", fruit: "Orange", user: "Gary" }],
    grouped = [];

dataResult.forEach(function (a) {
    if (!this[a.region]) {
        this[a.region] = { region: a.region, count: 0 };
        grouped.push(this[a.region]);
    }
    this[a.region].count++;
}, Object.create(null));
  
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var dataResult = [{ region: "Africa", fruit: "Orange", user: "Gary" }, { region: "Africa", fruit: "Apple", user: "Steve" }, { region: "Europe", fruit: "Orange", user: "John" }, { region: "Europe", fruit: "Apple", user: "bob" }, { region: "Asia", fruit: "Orange", user: "Ian" }, { region: "Asia", fruit: "Apple", user: "Angelo" }, { region: "Africa", fruit: "Orange", user: "Gary" }],
    grouped = [];

dataResult.forEach(function (a) {
    var key = [a.region, a.user].join('|');
    if (!this[a.region]) {
        this[a.region] = { region: a.region, count: 0 };
        grouped.push(this[a.region]);
    }
    if (!this[key]) {
        this[key] = true;
        this[a.region].count++;
    }
}, Object.create(null));
  
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var dataResult = [{ region: "Africa", fruit: "Orange", user: "Gary" }, { region: "Africa", fruit: "Apple", user: "Steve" }, { region: "Europe", fruit: "Orange", user: "John" }, { region: "Europe", fruit: "Apple", user: "bob" }, { region: "Asia", fruit: "Orange", user: "Ian" }, { region: "Asia", fruit: "Apple", user: "Angelo" }, { region: "Africa", fruit: "Orange", user: "Gary" }],
    grouped = [],               // result array
    hash = Object.create(null); // oposite of {}, this object does not contain any prototypes

dataResult.forEach(function (a) {

    // build key with region + name, spot pipe in hash
    var key = [a.region, a.user].join('|');

    // check if region is not in hash table
    if (!this[a.region]) {

        // create new object with region and count and insert it into hash table
        this[a.region] = { region: a.region, count: 0 };

        // push the object to the result
        grouped.push(this[a.region]);
    }

    // check if if not region and user exists, it means
    // the user in the region is not counted yet.
    if (!this[key]) {

        //create hash entry
        this[key] = true;

        // increment count 
        this[a.region].count++;
    }
}, hash);
  
console.log(hash);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Grouping array items based on string value

Grouping array items based on string value


By : Huynh Dao Truong
Date : March 29 2020, 07:55 AM
hop of those help? I am trying to group an array by sport. It could be n number of sports. Finally, then create a new array with it. Is there an efficient way to this without going overkill? , You can group the array like so:
code :
$sports = [
    ['sport' => 'soccer', 'id' => 97487],
    ['sport' => 'soccer', 'id' => 244800],
    ['sport' => 'soccer', 'id' => 258740],
    ['sport' => 'basketball', 'id' => 147884],
    ['sport' => 'baseball', 'id' => 222240],
    ['sport' => 'baseball', 'id' => 222245]
];

// we will build an array here where the key is the sport
// name and the value is an array of objects pertaining
// to that sport i.e. 'basketball' => [bb1, bb2, ...]

$array = array();

// now consider every sport object in your original array

foreach($sports as $key => $item)
{
   if (array_key_exists($item['sport'], $array)) {
     // we encountered this same sport in the past so we
     // know $array['sportName'] already exists and can
     // push right to it
     $array[$item['sport']][] = $item;
   } else {
     // we have never seen this sport before and now must
     // insert the sport into $array['sportName'] = []
     // and push this sport object to it
     $array[$item['sport']] = [$item];
   }
}

// since $array's keys are the names of the sports themselves, but
// you want the keys to be numeric, this will build a new array
// from just the values of $array which at this point contains
// grouped arrays of sport objects

$result = array_values($array);

// print the results for good measure :)

print_r($result);
Related Posts Related Posts :
  • Model aggregating in viewer - coordinate issue
  • Send post data like curl
  • sorting array with decimal value in specific order using javascript
  • Javascript - object.offsetTop and .offsetLeft gives 0
  • Remove content of p tag
  • Line 28: Expected an assignment or function call and instead saw an expression
  • How to trigger hover programmatically in chartjs
  • How to create a function to avoid repetitive steps?
  • Parameter the property used to filter an array
  • Return array with fast-csv in Node
  • If statement with parenthesis in javascript
  • Connecting the Javascript CSS to the CSS
  • Empty table cells
  • How to trouble shoot "NaN" error when the call to a function and assigning to let is the only visible issue
  • React / Javascript - how to filter data received to a filtered list of columns?
  • Javascript Await reserved keyword error inside if statement
  • How could I create an array on the fly?
  • How to make holes in polygons to display each one with clean colors on Google map?
  • Passing props to Children of Children (nested component tree)
  • onSelect option with get request
  • how can i test a computed property in vuejs using jest?
  • function not called after a change event
  • How to set a PHP session value as selected onclick on a drop down list
  • scrollIntoView does not include border
  • Javascript number comparison not correct
  • how to fix google map center location in vue js
  • Replace integer in a for loop with string
  • Replace nested JavaScript Object data item with dynamically created path?
  • Cannot remove item from shopping cart in React Redux reducer
  • How to import all images from a folder in ReactJS?
  • How to enforce Webpack 4 to detect and recompile only files that were changed
  • How to use arrow functions with main class 'this' properties?
  • Dynamically decide which Fetch response method to use
  • SVGRenderer with OrbitControls shows two SVG elements on opposite sides
  • JS nesting problem, variable comes back unidentified any way
  • An Alternative to <script> tag if resource don't get loaded
  • Javascript for loop behaviour in arrays
  • How to display two web content on same browser alternatively on click without reloading it?
  • How to call function inside the inner.html
  • React progress bar with each click
  • Copy text to clipboard from hidden input is not working in jQuery
  • How to populate all the array values to a single index in javascript
  • Checkbox input staying checked?
  • Change string on each loop iteration
  • React Native Fetch Requests are not getting sent to my Node Js backend for some users
  • jQuery Validation Add Method Regex Number with Parentheses
  • Do something if element equals value and is checked
  • display json data in bootstrap card using jquery
  • What prevents abuse of Firebase's createUserWithEmailAndPassword?
  • Karma + Jasmine (Angular Testing): Where should I define mock classes and test variables?
  • Call() method fails to generate output in javascript
  • Obj iteration dynamically - javascript
  • How to convert nested array to normal array and change types?
  • Javascript copy to clipboard only works if I have a breakpoint
  • Changing global variable by user input via function
  • different CSS style class on page load for mobile and desktop
  • JavaScript - Daterangepicker, isInvalidDate method enabling only one day
  • Javascript, Jquery: get element by two attr?
  • JavaScript colour changer doesn't work properly
  • Stop next execution of Rxjs observer?
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org