search

Home  >  Q&A  >  body text

Rewrite the title as: Group main array and add fields and subarrays in each grouping

<p>I have a heavy array like this: </p> <pre class="brush:php;toolbar:false;">[ {Id: 1, Name: 'Red', optionName: 'Color'}, {Id: 2, Name: 'Yellow', optionName: 'Color'}, {Id: 3, Name: 'Blue', optionName: 'Color'}, {Id: 4, Name: 'Green', optionName: 'Color'}, {Id: 7, Name: 'Black', optionName: 'Color'}, {Id: 8, Name: 'S', optionName: 'Size'}, {Id: 11, Name: 'M', optionName: 'Size'}, {Id: 12, Name: 'L', optionName: 'Size'}, {Id: 13, Name: 'XL', optionName: 'Size'}, {Id: 14, Name: 'XXL', optionName: 'Size'} ]</pre> <p>I need to group by <code>optionName</code> and have two rows in the main array, like this: </p> <pre class="brush:php;toolbar:false;">[ { Name: 'Color', Data:[{Id: 1, Name: 'Red'}, {Id: 2, Name: 'Yellow'}, {Id: 3, Name: 'Blue'}, {Id: 4, Name: 'Green'}, {Id: 7, Name: 'Black'}] }, { Name: 'Size', Data:[{Id: 8, Name: 'S'}, {Id: 11, Name: 'M'}, {Id: 12, Name: 'L'}, {Id: 13, Name: 'XL'}, {Id: 14, Name: 'XXL'}] } ]</pre> <p>How to implement it in javascript? </p>
P粉190443691P粉190443691484 days ago436

reply all(2)I'll reply

  • P粉409742142

    P粉4097421422023-08-25 18:44:16

    An ES6 solution using Map object:

    function groupBy(arr, key) {
      	return arr.reduce(
          (sum, item) => {
          	const groupByVal = item[key];
            groupedItems = sum.get(groupByVal) || [];
            groupedItems.push(item);
          	return sum.set(groupByVal, groupedItems);
            },
          new Map()
          );
    }
    
    var Data = [ 
    { Id: 1, Name: 'Red', optionName: 'Color' }, 
      { Id: 2, Name: 'Yellow', optionName: 'Color' },
      { Id: 3, Name: 'Blue', optionName: 'Color' },
      { Id: 4, Name: 'Green', optionName: 'Color' },
      { Id: 7, Name: 'Black', optionName: 'Color' },
      { Id: 8, Name: 'S', optionName: 'Size' },
      { Id: 11, Name: 'M', optionName: 'Size' },
      { Id: 12, Name: 'L', optionName: 'Size' },
      { Id: 13, Name: 'XL', optionName: 'Size' },
      { Id: 14, Name: 'XXL', optionName: 'Size' } ];
    
    document.getElementById("showArray").innerHTML =JSON.stringify([...groupBy(Data, 'optionName')], null, 4); 
    <pre id="showArray"></pre>

    reply
    0
  • P粉298305266

    P粉2983052662023-08-25 15:50:49

    Here is the code snippet I wrote for this situation. You can add this function to all arrays:

    Object.defineProperty(Array.prototype, 'group', {
      enumerable: false,
      value: function (key) {
        var map = {};
        this.forEach(function (e) {
          var k = key(e);
          map[k] = map[k] || [];
          map[k].push(e);
        });
        return Object.keys(map).map(function (k) {
          return {key: k, data: map[k]};
        });
      }
    });

    You can use it like this. You just pass a function that defines how to group the data.

    var newArray = arr.group(function (item) {
      return item.optionName;
    });

    Working Fiddle

    If necessary, you can replace {key: k, data: map[k]} with {Name: k, Data: map[k]}.


    This is also a more compact ES6 version of the above code:

    Object.defineProperty(Array.prototype, 'group', {
      enumerable: false,
      value: function (key) {
        let map = {};
        this.map(e => ({k: key(e), d: e})).forEach(e => {
          map[e.k] = map[e.k] || [];
          map[e.k].push(e.d);
        });
        return Object.keys(map).map(k => ({key: k, data: map[k]}));
      }
    });

    Use it like this:

    let newArray = arr.group(item => item.optionName))

    reply
    0
  • Cancelreply