首页 > 解决方案 > 我怎样才能改进我的代码?关于元素不重复

问题描述

我想知道该元素是否已经存在于我的列表中,因为我有存在功能

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) 通过这个函数changeIndexOnN​​ame()。

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)
}

标签: javascript

解决方案


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);


推荐阅读