admin管理员组

文章数量:1313082

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);

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);
Share Improve this question edited Nov 26, 2013 at 1:06 user3026304 asked Nov 24, 2013 at 1:34 user3026304user3026304 391 silver badge3 bronze badges 5
  • Any reason for those | ? Did you mean nested arrays? The end result is invalid syntax. – Benjamin Gruenbaum Commented Nov 24, 2013 at 1:38
  • Like most programming problems, you need to reason about the problem, e up with a suitable algorithm, and implement it. – Blue Skies Commented Nov 24, 2013 at 1:42
  • @BenjaminGruenbaum: while not technically invalid syntax, it definitely wasn't what the questioner intended to do. – Qantas 94 Heavy Commented Nov 24, 2013 at 1:44
  • 1 @Qantas94Heavy you're right, it's not invalid syntax - just amusing syntax with all those bitwise ors :) – Benjamin Gruenbaum Commented Nov 24, 2013 at 1:46
  • 1 This question is off topic because "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results". – Blue Skies Commented Nov 24, 2013 at 1:53
Add a ment  | 

3 Answers 3

Reset to default 10

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.

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]);
            }
        }
    }

}
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"}
];

var result = [] // THIS IS THE RESULTING ARRAY THAT YOU WANT

function find(age) {
    for (var i = 0; i < result.length; i++)
        if (result[i].age == age) return i
    return -1
}

function append(i, obj) {
    result[i].name.push(obj.name)
    result[i].color.push(obj.color)
}

for (var i = 0; i < items.length; i++) {
    var x = find(items[i].age)
    if (x < 0) result.push({ age: items[i].age, name: [items[i].name], color : [items[i].color]})
    else append(x, items[i])
}

console.log(result) // PRINT THE RESULT, alternatively you can use alert(result)

The output

[ { age: 16, name: [ 'Foo', 'foo' ], color: [ 'w', 'w' ] },
  { age: 18, name: [ 'Bar', 'bar', 'foobar' ], color: [ 'b', 'w', 'b' ] },
  { age: 20, name: [ 'barfoo' ], color: [ 'w' ] } ]

本文标签: javascriptSplit array of objects into new array or objects based on age valueStack Overflow