按数组中的多个属性对对象进行分组,然后对它们的值求和

2024-03-29

按多个属性对数组中的元素进行分组 https://codereview.stackexchange.com/questions/37028/grouping-elements-in-array-by-multiple-properties是与我的问题最接近的匹配,因为它确实通过数组中的多个键对对象进行分组。问题是这个解决方案不会对属性值求和然后删除重复项,而是将所有重复项嵌套在二维数组中。

预期行为

我有一个对象数组,必须按以下方式分组shape and color.

var arr = [
    {shape: 'square', color: 'red', used: 1, instances: 1},
    {shape: 'square', color: 'red', used: 2, instances: 1},
    {shape: 'circle', color: 'blue', used: 0, instances: 0},
    {shape: 'square', color: 'blue', used: 4, instances: 4},
    {shape: 'circle', color: 'red', used: 1, instances: 1},
    {shape: 'circle', color: 'red', used: 1, instances: 0},
    {shape: 'square', color: 'blue', used: 4, instances: 5},
    {shape: 'square', color: 'red', used: 2, instances: 1}
];

仅当此数组中的对象都是重复的时,才将其视为重复项shape and color是相同的。如果是的话我想分别总结一下used and instances值,然后删除重复项。

因此,在此示例中,结果数组可能仅包含四种组合:square red, square blue, circle red, circle blue

Problem

我在这里尝试了一种更简单的方法:

var arr = [
    {shape: 'square', color: 'red', used: 1, instances: 1},
    {shape: 'square', color: 'red', used: 2, instances: 1},
    {shape: 'circle', color: 'blue', used: 0, instances: 0},
    {shape: 'square', color: 'blue', used: 4, instances: 4},
    {shape: 'circle', color: 'red', used: 1, instances: 1},
    {shape: 'circle', color: 'red', used: 1, instances: 0},
    {shape: 'square', color: 'red', used: 4, instances: 4},
    {shape: 'square', color: 'red', used: 2, instances: 2}
];

result = [];

arr.forEach(function (a) {
    if ( !this[a.color] && !this[a.shape] ) {
        this[a.color] = { color: a.color, shape: a.shape, used: 0, instances: 0 };
        result.push(this[a.color]);
    } 
    this[a.color].used += a.used;
    this[a.color].instances += a.instances;
}, Object.create(null));

console.log(result);

但它输出

[{shape: "square", color: "red", used: 11, instances: 9},
{shape: "circle", color: "blue", used: 4, instances: 4}]

而不是预期的结果:

[{shape: "square", color: "red", used: 5, instances: 3},
{shape: "circle", color: "red", used: 2, instances: 1},
{shape: "square", color: "blue", used: 11, instances: 9},
{shape: "circle", color: "blue", used: 0, instances: 0}]

如何让我的函数按形状和颜色正确对对象进行分组?即总结它们的值并删除重复项?


Use 数组#reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce使用辅助对象对相似的对象进行分组。对于每个对象,检查组合是否shape and color存在于助手中。如果没有,请使用添加到帮助程序对象#分配 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign创建对象的副本,并将其推送到数组。如果是,请将其值添加到used and instances.

var arr = [{"shape":"square","color":"red","used":1,"instances":1},{"shape":"square","color":"red","used":2,"instances":1},{"shape":"circle","color":"blue","used":0,"instances":0},{"shape":"square","color":"blue","used":4,"instances":4},{"shape":"circle","color":"red","used":1,"instances":1},{"shape":"circle","color":"red","used":1,"instances":0},{"shape":"square","color":"blue","used":4,"instances":5},{"shape":"square","color":"red","used":2,"instances":1}];

var helper = {};
var result = arr.reduce(function(r, o) {
  var key = o.shape + '-' + o.color;
  
  if(!helper[key]) {
    helper[key] = Object.assign({}, o); // create a copy of o
    r.push(helper[key]);
  } else {
    helper[key].used += o.used;
    helper[key].instances += o.instances;
  }

  return r;
}, []);

console.log(result);

如果你可以使用 ES6,你可以使用Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map收集值,然后将其转换回数组传播 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator the 地图#值 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values:

const arr = [{"shape":"square","color":"red","used":1,"instances":1},{"shape":"square","color":"red","used":2,"instances":1},{"shape":"circle","color":"blue","used":0,"instances":0},{"shape":"square","color":"blue","used":4,"instances":4},{"shape":"circle","color":"red","used":1,"instances":1},{"shape":"circle","color":"red","used":1,"instances":0},{"shape":"square","color":"blue","used":4,"instances":5},{"shape":"square","color":"red","used":2,"instances":1}];

const result = [...arr.reduce((r, o) => {
  const key = o.shape + '-' + o.color;
  
  const item = r.get(key) || Object.assign({}, o, {
    used: 0,
    instances: 0
  });
  
  item.used += o.used;
  item.instances += o.instances;

  return r.set(key, item);
}, new Map).values()];

console.log(result);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按数组中的多个属性对对象进行分组,然后对它们的值求和 的相关文章

  • firebase.storage() 不是玩笑测试用例中的函数

    我正在使用 Jest 来测试我的 firebase 功能 这一切都在浏览器中进行 因此我与服务器端的 firebase 没有任何冲突 当我使用firebase auth or firebase database 一切正常 当我尝试使用时fi
  • 在 Node.js 中实现服务器发送事件的简单方法?

    我环顾四周 似乎在 Node js 中实现 SSE 的所有方法都是通过更复杂的代码 但似乎应该有一种更简单的方法来发送和接收 SSE 是否有任何 API 或模块可以让这件事变得更简单 这是一个每秒发送一个服务器发送事件 SSE 的 Expr
  • 移动浏览器上的 Javascript / jQuery 页面更改事件

    我正在设计一个移动网站 同时考虑所有领先的浏览器 Safari Chrome Dolphin Opera 我想显示一个 正在加载 元素页面导航 更改 请求新页面 我无法在锚标签上使用点击事件 因为有很多锚标签存在preventDefault
  • Java中如何对对象数组进行排序?

    我的数组不包含任何字符串 但它包含对象引用 每个对象引用都通过 toString 方法返回名称 id 作者和发布者 public String toString return name n id n author n publisher n
  • 如何使用 CSS 或 javascript 创建圆角

    复制 使用 CSS 创建圆角的最佳方法是什么 https stackoverflow com questions 7089 what is the best way to create rounded corners using css 7
  • 匹配 JavaScript RegEx 中的不可见字符

    我有一些包含不可见字符的字符串 但它们位于可预测的位置 通常 围绕我想要提取的文本片段 然后在第二次出现之后我想保留文本的其余部分 我似乎不知道如何关闭隐形字符 and将它们从我的结果中排除 为了匹配隐形 我一直在使用这个正则表达式 xA0
  • 如何在没有数据库的情况下创建AJAX分页?

    是否可以在没有 MySQL 帮助的情况下获取 AJAX 分页页面 难道我不能只添加一个包含我需要显示的文本和标记的 PHP 文件 然后通过单击页码将该内容提供给用户吗 那么可以用纯 jQuery 和 PHP 来实现吗 您会使用什么代码方法来
  • 如何使用 QuerySelector 获得第二个匹配项?

    以下语句给出了该类的第一个元素titanic element document querySelector titanic 我如何检索具有相同类的第二个元素 Use document querySelectorAll https devel
  • C 中指向常量字符串的指针

    char p string creates pointer to constant string char p string just an array with string 我只是有点困惑为什么它在第一个示例中创建一个指向常量字符串的指
  • 如何使用 ui-router 中的 ui-sref 将参数传递给控制器

    我需要传递和接收两个参数到我想要转换到的状态ui srefui router 的 例如使用下面的链接将状态转换为home with foo and bar参数 a Go to home state with foo and bar para
  • Chrome:window.print() 打印对话框仅在页面重新加载后打开 (javascript)

    我面临着一个非常奇怪的问题 我正在从 javascript 文件调用 window print 这在 Safari IE Firefox 中运行良好 直到两小时前 它在 Chrome 中也运行良好 版本29 0 1547 57 我没有更改我
  • 使用 jquery 时出现控制台错误 - Uncaught TypeError: Object # has no method

    我尝试使用以下 js 添加类或 css 样式 但出现控制台错误 var i 0 question i addClass show 收到以下控制台日志错误 Uncaught TypeError Object has no method add
  • 通过ajax POST提交两次表单

    插入到mysql using php通过文件调用AJAX 前insert语句php代码执行select查询到查找重复记录并继续insert statement Issue 从ajax调用php文件时 它执行了两次并得到作为重复记录的响应 好
  • 将命令行参数传递给 emscripten 生成的应用程序

    当使用 Emscripten 编译 C 程序时 会生成一个 HTML 页面来显示程序的结果 我想知道如何将命令行参数传递给应用程序 例如 对于原始的 C 程序 它是 bfs 32 1 我能够通过向生成的 html 文件添加一行来传递命令行参
  • 保存和恢复陷阱状态?管理多个陷阱处理程序的简单方法?

    有什么好的方法可以覆盖bash陷阱处理程序不会永久破坏可能已设置或尚未设置的现有处理程序 动态管理任意陷阱例程链怎么样 有没有办法保存陷阱处理程序的当前状态 以便以后可以恢复 在 Bash 中保存和恢复陷阱处理程序状态 我将提交以下堆栈实现
  • 在 PHP 中创建关联数组

    我有一个多维数组 shop array array appn1 pub1 pub2 pub3 array appn2 pub1 array appn3 pub1 pub2 每个数组中的第一项是申请编号每个数组中的其余部分是出版号 我得到每个
  • 您最喜欢的 JS/CSS 下拉菜单是什么? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 希望在网站上实现一个 只是好奇其他人都使用过什么以及他们有过什么样的体验 EDIT我也不是一个超级粉丝
  • 为什么 JavaScript 默认导出不可用?

    为什么默认导出不像命名导出那样实时 lib js export let counter 0 export function incCounter counter export default counter main1 js import
  • 如何连接/组合两个数组以连接成一个数组?

    我正在尝试将 JavaScript 中的 2 个数组合并为一个 var lines new Array a b c lines new Array d e f 这是一个简单的例子 我希望能够将它们组合起来 这样当读取第二行时 数组中的第四个
  • 具有值的 TextInput 不会更改值

    在我的react native应用程序中 我有一个API 我从中检索数据 并且我在输入值中设置数据 用户应该能够编辑这些输入并更新 但是当我尝试输入输入时它不会输入任何内容并且值保持原样 这是 TextInput 代码

随机推荐

  • 从地图中获取一段键

    有没有更简单 更好的方法从 Go 中的映射中获取键的切片 目前我正在迭代地图并将键复制到切片 i 0 keys make int len mymap for k range mymap keys i k i 这是一个老问题 但这是我的两分钱
  • 在 C# 中获取特定时区的日期时间时出现 System.TimeZoneNotFoundException 错误

    我有一个 JSON 文件 其中包含time zone范围 它的值如下London Casablanca Arizona Pacific Time US Canada 等 基于time zone 我想得到DateTime该时区的结果 例如 C
  • Ubuntu 17.04 上 sudo apt-get 更新失败

    运行时sudo apt get update在 ubuntu 17 04 Zesty Zapus 上 我收到以下错误 我已经在错误行上发布了 我想安装 python 库 如 matplotlib 和 tkinter 但由于上述命令未成功运行
  • CSS 文件和不需要的覆盖

    我有一个简单的 HTML 页面 它引用了 3 个 CSS 文件 第一个是仅适用于页面的样式表 另外两个是针对两个独特情态动词的样式 这些模态 CSS 文件不是我创建的 它们很高兴被使用分别地在整个网站的其他页面上 我的问题是 这两个模态 C
  • 1-2 秒后暂停 YouTube 视频

    我正在使用 Youtube Player api 在我的应用程序中播放 YouTube 视频 视频开始播放并在 1 2 秒后暂停 我创建了视频片段和视图组 随后我创建了一些 youtobe 视频视图 视频片段 public static f
  • OpenCV 中 minEnclosureCircle 的意外结果

    我最近使用了 OpenCV 2 4 2 的函数 minEnendingCircle 因为我需要测量一团点的直径 一段时间后 我意识到结果不正确 因此我决定编写一个小例程来计算一组非常小的点的直径 我测试了该函数 1个单点 连续2 4分 仅由
  • 保留一个新对象而无需获取关联

    我在广告实体中有以下映射 class Ad Id Column name id unique true nullable false GeneratedValue strategy GenerationType SEQUENCE gener
  • 实现 ActiveRecord before_find

    我正在使用缓存在表中的关键字构建搜索 在表中查找用户输入的关键字之前 它会被标准化 例如 删除了一些标点符号 如 并对大小写进行了标准化 然后使用规范化的关键字来查找获取搜索结果 我目前正在使用 before filter 处理控制器中的标
  • 导入 React-Router-Dom 后 React App 变为空白

    导入前react router一切正常 现在它构建成功但显示空白页面 这是我的代码 App js import ReactDOM from react dom client import BrowserRouter Routes Route
  • 如何调查 imp.load_module 上的 python2 段错误

    我正在尝试安装和使用dolfin https aur archlinux org packages dolfin bzr 在 Arch Linux 上 使用 Python 2 7 3 找出导致分段的原因的最佳方法是什么 诸如此类的故障 py
  • 无法获取在Firebase存储中上传的图像的实际下载网址[重复]

    这个问题在这里已经有答案了 我正在尝试获取上传到 firebase 数据库的图像的下载网址 但任务Uri imageURL storageReference getDownloadUrl 没有给出存储在 firebase 存储中的图像的实际
  • 实体框架 4 Single() vs First() vs FirstOrDefault()

    我花了很长时间寻找查询单个项目的不同方法的比较 以及何时使用每种方法 有谁有一个比较所有这些的链接 或者一个关于为什么你会使用其中一个而不是另一个的快速解释 还有更多我不知道的运营商吗 谢谢 以下是不同方法的概述 Find 当您想通过主键获
  • 如何对 Flask 应用程序进行守护进程?

    我有一个使用 Flask 用 Python 编写的小应用程序 现在我正在 nohup 下运行它 但我想将它守护进程化 这样做的正确方法是什么 部署 Flask 项目有多种方式 http flask pocoo org docs deploy
  • 在 Mac OS X Lion 上设置环境变量

    当有人说 编辑你的 plist 文件 或 你的 profile 或 bash profile 等时 这让我很困惑 我不知道这些文件在哪里 如果必须这样做的话如何创建它们等等 也不知道为什么似乎有这么多不同的文件 为什么 它们做不同的事情吗
  • 实现 PushKit 并测试开发行为

    我想在我的应用程序 Voip 应用程序 中实现 PushKit 服务 但我有以下疑问 我看到我只能生成生产 voip 证书 如果我尝试在开发设备上测试 voip 推送通知服务 它可以工作吗 这是我的实施测试 通过这 3 行代码 我可以在 d
  • 将 Shapes.Path 项目绑定到 ItemsControl

    我一直在试图弄清楚如何绑定ObservableCollection
  • 超越比较忽略所有文件中不重要的差异

    我正在使用Beyond Compare 3 3 4 我想比较大量文件并忽略不重要的差异 In Session gt Session Settings gt Comparison tab 需要打开文件 部分有一个 比较内容 基于规则的比较 当
  • IE 11 中的 VueJS - 的模板包装器不工作,但在 Edge 和 Chrome 中工作

    这是在 IE 11 中使用 Vue 2 5 16 假设datasetapp data 中的数组 以下内容在 Chrome 中运行良好 并且代码已简化 tbody tbody
  • 如何在 iOS 应用程序中创建自定义委托

    在 iPhone 中 每个 UIContrrol 都有预定义的委托方法 但是我们如何创建自己的自定义委托方法 在你的头文件中 之前 interface insert protocol YourDelegate
  • 按数组中的多个属性对对象进行分组,然后对它们的值求和

    按多个属性对数组中的元素进行分组 https codereview stackexchange com questions 37028 grouping elements in array by multiple properties是与我