javascript - 我怎样才能改进我的代码?关于元素不重复
问题描述
我想知道该元素是否已经存在于我的列表中,因为我有存在功能
function exist(colection,newItem,newIndex) {
let theName = changeIndexOnName(newItem,newIndex)
const exist = colection.find( item =>(theName === item.name))
return !!exist
}
我不想重复我的元素的名称,这就是为什么我这样列出它们:(element-1, element-2, element-3...element-n) 通过这个函数changeIndexOnName()。
function add(colection, newItem) {
let allowedIndex = 0
while(exist(colection, newItem, allowedIndex)){
allowedIndex++
}
newItem.name = changeIndexOnName(newItem.name, allowedIndex)
colection.push(newItem)
return colection
}
一旦我有可用的号码,我就会在那里更改号码的名称。 newItem.name = changeIndexOnName(newItem.name, allowedIndex)
这是开始,我有两个数组,我想将新元素放入旧元素列表中
for (const e of newElements) {
add(olderElements, e)
}
解决方案
filter
您可以使用as直接查找新索引let allowedIndex = colection.filter(item => item.name.split('-')[0] === newItem.name).length;
。
在下面试试。
let olderElements = [{name: "Collection"}];
let newElements = [{name: "Collection"}, {name: "Collection"}];
function changeIndexOnName(name, allowedIndex) {
return name + (allowedIndex === 0 ? "" : ("-" + allowedIndex));
}
function add(colection, newItem) {
let allowedIndex = colection.filter(item => item.name.split('-')[0] === newItem.name).length;
newItem.name = changeIndexOnName(newItem.name, allowedIndex)
colection.push(newItem)
return colection;
}
for (const e of newElements) {
add(olderElements, e);
}
console.log(olderElements);
推荐阅读
- java - 生成器是抽象的;无法实例化。为什么?
- python-packaging - 管理 python 依赖项以安装其他包
- javascript - Javascript Promise - 拒绝或解析数据库中的空结果
- c# - 如何使自定义按钮响应更流畅?
- angular - 在 Angular 中,是否可以在模板内部创建一个复制对象?
- amazon-web-services - docker with AWS:在 docker 容器内的哪个目录是寻找 AWS 凭证的?
- c++ - 存储 gsl::span 的 std::vector
没有按预期工作 - flutter - 如何在 Flutter 中动态生成小部件?
- android - 如何让android模拟器连接到我们服务器上的特定端口
- botframework - 有没有办法在机器人框架中垂直堆叠建议的操作?