Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array of objects into new array or objects based on age value

Split array of objects into new array or objects based on age value in Javascript

var items = [
    {name:"Foo", age:16, color:"w"},
    {name:"Bar", age:18, color:"b"},
    {name:"foo", age:16, color:"w"},
    {name:"bar", age:18, color:"w"},
    {name:"foobar", age:18, color:"b"},
    {name:"barfoo", age:20, color:"w"}
];

How can I return a list like:

var items = [
    {age:16,name:"Foo"|"foo",gender:"w"|"w"},
    {age:18,name:"Bar"|"bar"|"foobar",gender:"b"|"w"|"b"},
    {age:20,name:"barfoo",gender:"w"}
];

I have worked but i got output with 'undefined' in name. Below is my code.

var data = [{age: 21,name: "Walter",color: "black"},{age: 25,name: "sentinel",color: "black"
},{age: 21,name: "Micah",color: "purple"},{age: 25,name: "mike",color: "black"},{age: 21,name: "Danny",color: "white"},{age: 25,name: "mike",color: "black"}];
var obj=data;
var arrayobj = obj.length;
var i, row, arr = obj, ss = {};
for (i = 0; i < arr.length; i++) {
    row = arr[i];   
    ss[row.age] = ss[row.age] || {count: 0};
    if (ss[row.age][row.age] === undefined) {                          
        ss[row.age][row.name] = row.name;
        ss[row.age]['name']+=row.name+'|';
        ss[row.age]['color']+=row.color+'|';
        ss[row.age]['count'] += 1;
    }
}
console.table(ss);
like image 408
user3026304 Avatar asked Jul 13 '26 05:07

user3026304


2 Answers

I'm assuming you want to group the items by their age. Here is one way:

(fiddle)

items.reduce(function(buckets,item){
    if(!buckets[item.age]) buckets[item.age] = [];
    buckets[item.age].push(item);
    return buckets;
},{});

Let's explain:

  • For each item, if we don't already have a 'bucket' for it, create a new empty one
  • Add it to the bucket
  • return the new updated bucket list.

The method returns an object with 3 properties: 16,18 and 20, each containing the objects with that age.

like image 78
Benjamin Gruenbaum Avatar answered Jul 15 '26 19:07

Benjamin Gruenbaum


This will work. The output is in different format than one provided by exebook .

Please check and confirm. Here's a fiddle....

** UX Manager

var buckets = [];

for (var item in items) {
    var currentAge = items[item].age;

    if(!buckets[currentAge]) {
        buckets[currentAge] = [];
        for (var i in items) {      
            if (currentAge === items[i].age) {
                buckets[currentAge].push(items[i]);
            }
        }
    }

}
like image 44
nasigoreng Avatar answered Jul 15 '26 18:07

nasigoreng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!