Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - reduce array to a by grouping objects with same property

I have an array of objects and I am trying to group them by similar property value. So lets say here is array

[  
  {  
    "size":"6.5",
    "width":"W"
  },
  {  
    "size":"6.5",
    "width":"M"
  },
  {  
    "size":"7.5",
    "width":"w"
  },
  {  
    "size":"8",
    "width":"M"
  },
  {  
    "size":"8",
    "width":"w"
  }
]

and i am trying to get something like this

[  
  {  
    "size_new":"6.5",
    "width_group":[  
      "W",
      "M"
    ]
  },
  {  
    "size_new":"7.5",
    "width_group":[  
      "M"
    ]
  },
  {  
    "size_new":"8",
    "width_group":[  
      "w",
      "M"
    ]
  }
]

My js looks like this

var _x = [];

for(var i = 0; i < x.length; i++){
    if(x[i].size == x[i+1].size){
        _x[i] = {
            new_size: x[i].size,
            width_group: [x[i].width,x[i+1].width]
        }
    }
}

Here is my fiddle http://jsfiddle.net/sghoush1/ogrqg412/1/

I am pretty sure that there is probably a giant gaping hole in my logic

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One simple way to do this would be to break this into several steps:

var sizeSorter = function(a, b) {return a - b};
var sizes = data.reduce(function(acc, item) {
    (acc[item.size] || (acc[item.size] = [])).push(item.width);
    return acc;
}, {}); //=> {8: ['M', 'W'], '6.5': ['W', 'M'], '7.5': ['W']}
Object.keys(sizes).sort(sizeSorter).map(function(size) {
    return {size_new: size, width_group: sizes[size]};
});

That sorting is necessary because the keys will be sorted in Array order, with small numbers like '8' before strings like '6.5'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...