JavaScript-对数组进行分组,然后根据长度对分组结果排序

发布于 2025-01-29 20:49:56 字数 1235 浏览 2 评论 0原文

这是阵列;

var dataArr = [
  {
    "permalink": /* link*/
      "subreddit": "mac"
  }, {
    "permalink": /* link*/
      "subreddit": "worldnews"
  }, {
    "permalink": /* link*/
      "subreddit": "MushroomGrowers"
  }, {
    "permalink": /* link*/
      "subreddit": "chrome"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "SquaredCircle"
  }.....
]

基于“ subreddit”键的分组似乎

简单

{
  ArtisanVideos: [
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    }
  ],
  chrome: [
    {
      "permalink": ' link ',
      subreddit: "chrome"
    }
  ],
  laravel: [
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    }
  ],
  mac: [
    {
      "permalink": ' link ',
      subreddit: "mac"
    }
  ]
}

很 阵列的长度

this is the array ;

var dataArr = [
  {
    "permalink": /* link*/
      "subreddit": "mac"
  }, {
    "permalink": /* link*/
      "subreddit": "worldnews"
  }, {
    "permalink": /* link*/
      "subreddit": "MushroomGrowers"
  }, {
    "permalink": /* link*/
      "subreddit": "chrome"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "SquaredCircle"
  }.....
]

grouping seems simple enough based on the "subreddit" key using underscore

const grouped = _.groupBy( dataArr, 'subreddit' )

returns an object something like this

{
  ArtisanVideos: [
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    }
  ],
  chrome: [
    {
      "permalink": ' link ',
      subreddit: "chrome"
    }
  ],
  laravel: [
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    }
  ],
  mac: [
    {
      "permalink": ' link ',
      subreddit: "mac"
    }
  ]
}

Now, how do I sort the grouped objects based on the length of the array

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贵在坚持 2025-02-05 20:49:56

从我上述评论...

“如果OP 取决于 对对象的关键插入顺序(尽管它甚至可以工作)(因为这是OP的要求),则OP的整个数据处理方法是在疑问。

问题

为了实现中间分组目标,一个人将

降低 给定的数据 - 结构为分组条目的对象( /Developer.mozilla.org/en-us/docs/web/javascript/Reference/global_objects/objects/object/entries“ rel =“ nofollow noreferrer”> entries 现在可以是 map ped进入仍然是未排序的结果数组的对象,在最后一步中将是 sort 由每个对象的唯一数组-Value length - property或通过语言环境比较单个属性名称(键) )。

function groupAndCollectBySameKeyValue({ key, result }, item) {
  const groupValue = item[key];
  (result[groupValue] ??= []).push(item);
  return { key, result };
}

var dataArr = [
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'mac' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'chrome' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
];
console.log(
  dataArr
    .reduce(groupAndCollectBySameKeyValue, {
      key: 'subreddit',
      result: {},
    })
    .result
);
console.log(
  Object
    .entries(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    )
    // create object from grouped entry (key-value pair).
    .map(([key, value]) => ({ [key]: value }))
    .sort((a, b) =>
      // ... either by array length ...
      Object.values(b)[0].length - Object.values(a)[0].length
      // ... or by locale alphanumeric precedence.
      || Object.keys(a)[0].localeCompare(Object.keys(b)[0])
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

原因之一也可以实现OP的最初目标,但不建议实现。一个人不应真正取决于对象的密钥插入顺序。

function groupAndCollectBySameKeyValue({ key, result }, item) {
  const groupValue = item[key];
  (result[groupValue] ??= []).push(item);
  return { key, result };
}

var dataArr = [
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'mac' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'chrome' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
];
console.log(
  dataArr
    .reduce(groupAndCollectBySameKeyValue, {
      key: 'subreddit',
      result: {},
    })
    .result
);
console.log(
  Object
    .entries(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    )
    .sort(([aKey, aValue], [bKey, bValue]) =>
      // array length first, or locale property name comparison.
      bValue.length - aValue.length || aKey.localeCompare(bKey)
    )
    .reduce((result, [key, value]) =>
      // create object by aggregating entries while following
      // the above sorted key precedence / key insertion order.
      Object.assign(result, { [key]: value }), {}
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

From my above comment ...

"In case the OP depends on key insertion order (though it would even work) of an object (because this is what the OP is asking for) then the OP's entire data handle approach is at question. What one could do instead ... create a sorted array of object-items from the former object of grouped entries."

The next provided solution does exactly what already got proposed.

In order to achieve the intermediate grouping goal one would reduce the given data-structure into an object of grouped entries (each entry holding an array of some of the former data-array items.

Each of the entries now can be mapped into an own object of the still unsorted result array which within a last step will be sorted by either each object's sole array-value length-property or by a locale comparison of the single property names (keys).

function groupAndCollectBySameKeyValue({ key, result }, item) {
  const groupValue = item[key];
  (result[groupValue] ??= []).push(item);
  return { key, result };
}

var dataArr = [
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'mac' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'chrome' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
];
console.log(
  dataArr
    .reduce(groupAndCollectBySameKeyValue, {
      key: 'subreddit',
      result: {},
    })
    .result
);
console.log(
  Object
    .entries(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    )
    // create object from grouped entry (key-value pair).
    .map(([key, value]) => ({ [key]: value }))
    .sort((a, b) =>
      // ... either by array length ...
      Object.values(b)[0].length - Object.values(a)[0].length
      // ... or by locale alphanumeric precedence.
      || Object.keys(a)[0].localeCompare(Object.keys(b)[0])
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

One of cause can achieve the OP's original goal as well but it is not recommended. One should not really depend on an object's key insertion order.

function groupAndCollectBySameKeyValue({ key, result }, item) {
  const groupValue = item[key];
  (result[groupValue] ??= []).push(item);
  return { key, result };
}

var dataArr = [
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'mac' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'chrome' },
  { permalink: 'link', subreddit: 'ArtisanVideos' },
  { permalink: 'link', subreddit: 'laravel' },
];
console.log(
  dataArr
    .reduce(groupAndCollectBySameKeyValue, {
      key: 'subreddit',
      result: {},
    })
    .result
);
console.log(
  Object
    .entries(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    )
    .sort(([aKey, aValue], [bKey, bValue]) =>
      // array length first, or locale property name comparison.
      bValue.length - aValue.length || aKey.localeCompare(bKey)
    )
    .reduce((result, [key, value]) =>
      // create object by aggregating entries while following
      // the above sorted key precedence / key insertion order.
      Object.assign(result, { [key]: value }), {}
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文