查找最单击的'在javaScript中给定的一系列变体中的变体
我有一系列称为articles
的对象。一篇文章具有3个重要属性。 名称
,<代码>单击和variants
。 variants
属性也是包含name
的对象数组(它对应于数组articles
中的文章)。 最有效的方法找到每个文章最单击的变体是什么?
我认为也许有某种方法可以使用地图或传播操作员,但我不了解语法。我认为我可以为每组最单击的文章创建一个“词典”,但是有一个简单的方法吗?
输入:
[
{name: "article1",
clicks: 10,
variants: ["article2", "article3"]},
{name: "article2",
clicks: 7,
variants: ["article1", "article3"]},
{name: "article3",
clicks: 15,
variants: ["article1", "article2"]},
{name: "article4",
clicks: 3,
variants: ["article5"]},
{name: "article5",
clicks: 6,
variants: ["article4"]},
]
所需的输出:
{name: "article1",
clicks: 10,
variants: ["article2", "article3"],
mostClickedVariant: "article3"}
{name: "article2",
clicks: 7,
variants: ["article1", "article3"],
mostClickedVariant: "article3"},
等。每篇文章
I have an array of objects called articles
. An article has 3 important properties. name
, clicks
, and variants
. The variants
property is also an array of objects that contain name
(It corresponds to an article in the array articles
). What is the most efficient way to find each article's most clicked variant?
I thought maybe there was some way to use a map or spread operator, but I don't understand the syntax. I think I could create a 'dictionary' with the most clicked article for each set, but is there an easier way?
Input:
[
{name: "article1",
clicks: 10,
variants: ["article2", "article3"]},
{name: "article2",
clicks: 7,
variants: ["article1", "article3"]},
{name: "article3",
clicks: 15,
variants: ["article1", "article2"]},
{name: "article4",
clicks: 3,
variants: ["article5"]},
{name: "article5",
clicks: 6,
variants: ["article4"]},
]
Desired output:
{name: "article1",
clicks: 10,
variants: ["article2", "article3"],
mostClickedVariant: "article3"}
{name: "article2",
clicks: 7,
variants: ["article1", "article3"],
mostClickedVariant: "article3"},
etc. for each article
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此版本不会突变原始版本,只需返回带有新属性的副本即可。它还使用一种更有效的方法来查找最大值,将列表减少到
o(n)
时间,而不是使用o(n log n)
sort
。我们首先创建一个索引将文章名称映射到他们的点击计数中,然后使用助手
maxby
,我们创建一个函数,findmax
,可以找到与最大的名称相关的名称点击计数。然后,我们只需映射元素,用新的
mostClickedVariant
通过调用findmax
用变体名称列表确定的属性。This version does not mutate the original, just returns a copy with the new properties added. It also uses a more efficient way to find maxima, reducing the list to its maximum in
O (n)
time, rather than using anO (n log n)
sort
.We first create an index mapping the article names to their click counts, and, using the helper
maxBy
, we create a function,findMax
that will find the name associated with the largest click count.Then we simply map over the elements, returning copies with new
mostClickedVariant
properties determined by callingfindMax
with the list of variant names.尝试一下(我在以下代码段中添加了所有描述性评论):
Try this (I added all the descriptive comments in the below code snippet) :