javascript - 有没有更好的方法来检查数组中的相似性?
问题描述
我得到一个返回的响应和一个哈希数组。哈希数组有两个键“title”和“paragraph”。有时我会收到在段落键中返回相似值的响应。
例如,当我只返回段落中的值时:
["Welcome to the best place", "Welcome to the best place in the world, Boston!"]
您会看到索引 0 处包含索引 1 处的内容
我正在映射哈希数组以返回其中一个键“段落”。然后,如果该值等于数组中的任何其他元素,我会尝试过滤掉第一个元素。我有一些东西只有在数组具有与上述状态相似的值时才有效,并且如果它失败将返回一个空数组。
const description = hotel
.description()
.map(descriptions => descriptions.paragraph)
.filter((paragraph, index) => !paragraph[index].includes(paragraph[0]))
Wherehotel.description()
返回哈希数组,要过滤的映射链将返回数组中的结果
上面的示例代码返回一个有效的响应,其中数组:
["Welcome to the best place", "Welcome to the best place in the world, Boston!"]
变成:
["Welcome to the best place in the world, Boston!"]
但是如果返回的数组是唯一的,则返回一个空数组。
预期结果是:
["You are here at the best place", "Welcome to the best place in the world, Boston!"]
实际结果是:
[]
不确定要附加到该链上以使其返回唯一值。
解决方案
我正在简化您的示例以使用它,但这个概念仍然适用于此。我也在做以下假设:
- “类似”的意思是“包括”
- 您会对所有相似之处感兴趣,而不仅仅是与第一个相似之处
- 您的原始数据没有严格的重复短语(虽然这可以解决)
- 您更喜欢删除子集短语并保留超集短语(如果这有意义的话)。
如果是这样,那么以下方法似乎可以满足您的需求:
let greetings = [
"Welcome to the best place",
"Welcome to the best place in the world, Boston!"
];
let condensed =
greetings
.filter(g =>
!greetings.some(other => other.includes(g) && !(other == g))
);
console.log(condensed);
当所有值都不相似时,这里它不会返回一个空数组:
let greetings = [
"You're at the best place",
"Welcome to the best place in the world, Boston!"
];
let condensed =
greetings
.filter(g =>
!greetings.some(other => other.includes(g) && !(other == g))
);
console.log(condensed);
推荐阅读
- node.js - Performance between local database and cloud database
- clojurescript - 为什么 let-defined atom 会提供不同的结果?
- html - 如何使用角度材料或引导程序在进度条上显示垂直可移动时间线
- cognos-11 - 在 Cognos Analytics 11 中更改搜索和选择提示中的默认选项
- javascript - 始终设置一个 cookie 以响应 true
- angular - 如何使用订阅测试组件
- c# - 范围报告中所用的总时间未正确显示
- python - 我如何将 str 转换为 float (外键的值)
- angular - 我可以集成两个 Angular 10 项目吗?
- sql - SQL - 在查询中选择内选择