reduce array to a by grouping objects with same property

前端 未结 2 1395
庸人自扰
庸人自扰 2020-12-12 05:46

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\":\         


        
相关标签:
2条回答
  • 2020-12-12 06:49

    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'.

    0 讨论(0)
  • 2020-12-12 06:53

    You need to search if you have already added a specific size and then update only its width. Otherwise insert a new object

    var _x = x.reduce(function(p,v){
        var existing = p.filter(function(item){return item.new_size === v.size})[0];
        if (existing){
            existing.width_group.push( v.width );
        } else {
            p.push( {
                new_size: v.size,
                width_group:[v.width]
            } );
        }
        return p;
    },[]);
    

    Demo at http://jsfiddle.net/ogrqg412/3/

    0 讨论(0)
提交回复
热议问题