- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对在 Javascript 中分组有疑问。
我有一个如下所示的数组,其中每个项目保证只有 is_sweet
、is_spicy
或 is_bitter
中的一个相等为 true
:
const foodsData = [{
name: 'mie aceh',
is_sweet: false,
is_spicy: true,
is_bitter: false,
}, {
name: 'nasi padang',
is_sweet: false,
is_spicy: true,
is_bitter: false,
}, {
name: 'serabi',
is_sweet: true,
is_spicy: false,
is_bitter: false,
}, {
name: 'onde-onde',
is_sweet: true,
is_spicy: false,
is_bitter: false,
}, {
name: 'pare',
is_sweet: false,
is_spicy: false,
is_bitter: true,
}];
我想要的输出是根据第一个元素的 is_sweet、第二个元素的 is_bitter 和第三个元素的 is_spicy 对数组进行分组,如下所示:
[
[
{ name: 'serabi',
is_sweet: true,
is_spicy: false,
is_bitter: false },
{ name: 'onde-onde',
is_sweet: true,
is_spicy: false,
is_bitter: false }
],
[
{ name: 'pare',
is_sweet: false,
is_spicy: false,
is_bitter: true }
],
[
{ name: 'mie aceh',
is_sweet: false,
is_spicy: true,
is_bitter: false },
{ name: 'nasi padang',
is_sweet: false,
is_spicy: true,
is_bitter: false }
]
]
我尝试通过编写下面的代码来做到这一点
const isSweet = foodsData.filter(food => food.is_sweet);
const isBitter = foodsData.filter(food => food.is_bitter);
const isSpicy = foodsData.filter(food => food.is_spicy);
const newFood = [];
newFood.push(isSweet);
newFood.push(isBitter);
newFood.push(isSpicy);
有没有一种方法可以使用原始 Javascript 或 Lodash 获得相同的结果但代码更清晰?
最佳答案
您已经阐明每个项目只能具有三个属性之一 is_sweet
/is_spicy
/is_bitter
等于true
.
鉴于此假设,一种方法是我们可以根据数量值对项目进行分组 x.is_sweet*4 + x.is_spicy*2 + x.is_bitter*1
对于项目 x
.对于那些只有 is_bitter: true
的人,这个数量等于 1 , 2 对于只有 is_spicy: true
的项目, 4 对于只有 is_sweet: true
的项目.
根据该数量分组后,您可以使用 _.values
摆脱由 _.groupBy
创建的 key :
_.values(_.groupBy(foodsData, x => x.is_sweet*4 + x.is_spicy*2 + x.is_bitter*1))
显然,您可以为谓词指定一个描述性名称:
const flavour = food => food.is_sweet*4 + food.is_spicy*2 + food.is_bitter*1;
let groupedFoods = _.values(_.groupBy(foodsData, flavour))
请注意,如果允许项目具有这三个键中的多个键为真,则上面的代码仍会给出合理的结果,因为您将拥有与 [is_sweet, is_spicy, is_bitter]
相关的八组。等于[0,0,0]
, [0,0,1]
, [0,1,0]
, [0,1,1]
, [1,0,0]
, [1,0,1]
, [1,1,0]
, 和 [1,1,1]
.
事后看来,我们不需要谓词 flavour
为每个条目拉出一个数字 food
;根据上一段,如果它提取三个值,我们会很高兴 food.is_sweet
, food.is_spicy
, 和 food.is_bitter
, 并将它们放在一个数组中。 Lodash 有 _.over
为此,我们可以定义
const flavour = _.over([is_sweet, is_spicy, is_bitter]);
关于上述解决方案的可读性的几句话。
_.groupBy
是比 reduce
更高层次的抽象- 类似(成员(member)或免费)功能;换句话说,后者的功能比问题中用例所需的功能强大得多,因此它们的表现力不如前者。事实上,_.groupBy
很可能根据 reduce
来实现.这是一个残酷的实现来证明这是可能的:
const groupBy = (things, f) => {
return things.reduce((acc, item) => {
if (acc[f(item)] == undefined)
acc[f(item)] = [item];
else
acc[f(item)].push(item);
return acc;
}, {});
}
// both these give the same result:
groupBy([1,2,3,4,4,4], x => x % 2 == 0); // mine
_.groupBy([1,2,3,4,4,4], x => x % 2 == 0); // lodash's
解决方案在文字上非常简短:它看起来多么“复杂”或“花哨”并不重要;一旦您习惯了这种做事方式(也就是正确的方式),您就会阅读代码。再看一遍:
_.values(_.groupBy(foodsData, flavour))
这已经相当可读了,但是如果你使用 lodash/fp
模块,你甚至可以改进它:
_.values(_.groupBy(flavour, foodsData))
这与下面的英文句子有多远?
"get the values of the result of grouping by flavor the foods"
说不可读就意味着否认事物的真实性。
使用较低杠杆结构的较长解决方案,例如 for
循环或(好一点)reduce
-like 实用程序会强制您解析 代码。如果不仔细检查它们的 body ,您就无法理解这些溶液的作用。即使您决定拉取函数 (acc, item) => { … }
退出 reduce
的通话并为其命名,以 input.reduce(<i>fun</i>, <i>acc</i>)
结尾你怎么给它起名字?它是一个在中间结果中将元素推到数组顶部的函数。除非在琐碎的用例中,否则您不会为这样满嘴的东西找到一个好名字。您只是将问题转移到其他地方。阅读这段代码的人仍然会感到困惑。
_.over
也可能有点可怕:
const flavour = _.over([is_sweet, is_spicy, is_bitter]);
但实际上,你只是学习并接受什么,这需要付出什么代价_.over
方法?我的意思是,这就像学习一门新语言,仅此而已。 And the explanation of _.over
is fairly simple :
_.over([iteratees=[_.identity]])
Creates a function that invokes
iteratees
with the arguments it receives and returns their results.
就是这么简单:_.over(['a', 'b', 'd'])({a: 1, b: 2, c: 3}) == [1, 2, undefined]
关于javascript - 如何对具有多个属性的数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70844485/
我正在尝试创建一个包含 int[][] 项的数组 即 int version0Indexes[][4] = { {1,2,3,4}, {5,6,7,8} }; int version1Indexes[
我有一个整数数组: private int array[]; 如果我还有一个名为 add 的方法,那么以下有什么区别: public void add(int value) { array[va
当您尝试在 JavaScript 中将一个数组添加到另一个数组时,它会将其转换为一个字符串。通常,当以另一种语言执行此操作时,列表会合并。 JavaScript [1, 2] + [3, 4] = "
根据我正在阅读的教程,如果您想创建一个包含 5 列和 3 行的表格来表示这样的数据... 45 4 34 99 56 3 23 99 43 2 1 1 0 43 67 ...它说你可以使用下
我通常使用 python 编写脚本/程序,但最近开始使用 JavaScript 进行编程,并且在使用数组时遇到了一些问题。 在 python 中,当我创建一个数组并使用 for x in y 时,我得
我有一个这样的数组: temp = [ 'data1', ['data1_a','data1_b'], ['data2_a','data2_b','data2_c'] ]; // 我想使用 toStr
rent_property (table name) id fullName propertyName 1 A House Name1 2 B
这个问题在这里已经有了答案: 关闭13年前。 Possible Duplicate: In C arrays why is this true? a[5] == 5[a] array[index] 和
使用 Excel 2013。经过多年的寻找和适应,我的第一篇文章。 我正在尝试将当前 App 用户(即“John Smith”)与他的电子邮件地址“jsmith@work.com”进行匹配。 使用两个
当仅在一个边距上操作时,apply 似乎不会重新组装 3D 数组。考虑: arr 1),但对我来说仍然很奇怪,如果一个函数返回一个具有尺寸的对象,那么它们基本上会被忽略。 最佳答案 这是一个不太理
我有一个包含 GPS 坐标的 MySQL 数据库。这是我检索坐标的部分 PHP 代码; $sql = "SELECT lat, lon FROM gps_data"; $stmt=$db->query
我需要找到一种方法来执行这个操作,我有一个形状数组 [批量大小, 150, 1] 代表 batch_size 整数序列,每个序列有 150 个元素长,但在每个序列中都有很多添加的零,以使所有序列具有相
我必须通过 url 中的 json 获取文本。 层次结构如下: 对象>数组>对象>数组>对象。 我想用这段代码获取文本。但是我收到错误 :org.json.JSONException: No valu
enter code here- (void)viewDidLoad { NSMutableArray *imageViewArray= [[NSMutableArray alloc] init];
知道如何对二维字符串数组执行修剪操作,例如使用 Java 流 API 进行 3x3 并将其收集回相同维度的 3x3 数组? 重点是避免使用显式的 for 循环。 当前的解决方案只是简单地执行一个 fo
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我有来自 ASP.NET Web 服务的以下 XML 输出: 1710 1711 1712 1713
如果我有一个对象todo作为您状态的一部分,并且该对象包含数组列表,则列表内部有对象,在这些对象内部还有另一个数组listItems。如何更新数组 listItems 中 id 为“poi098”的对
我想将最大长度为 8 的 bool 数组打包成一个字节,通过网络发送它,然后将其解压回 bool 数组。已经在这里尝试了一些解决方案,但没有用。我正在使用单声道。 我制作了 BitArray,然后尝试
我们的数据库中有这个字段指示一周中的每一天的真/假标志,如下所示:'1111110' 我需要将此值转换为 boolean 数组。 为此,我编写了以下代码: char[] freqs = weekday
我是一名优秀的程序员,十分优秀!