不允许数组中的项具有相同的值

时间:2018-02-02 15:36:00

标签: arrays angular typescript

我现在正在工作的东西对我的大脑来说有点复杂。我已经获得了一些数据,并且该数据有一个字段'位置,并且根据该位置,它们将按照该顺序显示在客户端(例如,最后一个项目)用户已添加,他可以将其位置更改为1,在客户端将首先显示,然后显示其余数据),并且他可以随时更改位置(从1到8,然后它将显示为最后因为该数据的数量限制为最多8)。 但问题是当用户将位置例如从4更改为1,并且已经存在位置为1的数据时,那么我们必须具有相同位置的项目,这不应该发生。是否有解决方案来检查数组,检查相同的值然后替换它们?

实施例: 有2个项目,项目1有位置1,项目2有位置2.如果我们将项目2的位置改为1,那么它们都会有一个,但是项目1应该自动增加到2。

我到目前为止所做的是对数组进行forEach,并检查条件值但是效果不佳。是否有一些算法来实现这一目标?

function bootMyTrait ()
{
    if ($this instanceOf awesomeInterface)
    {
        $this->append('nice_attribute');
    }
}

这是我检查和更改数组项及其位置的代码。

1 个答案:

答案 0 :(得分:1)

赞赏这个要点:https://gist.github.com/albertein/4496103

如果我理解正确,你会想要链接中显示的内容,所以当“TypeScriptifying”它并使其适用于你的(简化)案例时:

array = [1, 2, 3, 4, 5];

move(array, element, delta) {
  let index = array.indexOf(element);
  let newIndex = index + delta;

  //Already at the top or bottom.
  if (newIndex < 0 || newIndex == array.length) return; 

  let indexes = [index, newIndex].sort(); //Sort the indexes
  //Replace from lowest index, two elements, reverting the order
  array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]); 
}

moveUp(element) {
  this.move(this.array, element, -1);
}

moveDown(element) {
  this.move(this.array, element, 1);
}

和相应的HTML:

<div *ngFor="let a of array">
  {{a}} 
  <button (click)="moveUp(a)">Move Up</button>
  <button (click)="moveDown(a)">Move Down</button>
</div>

StackBlitz

这也可以给你一些灵感:Move an array element from one array position to another:)

相关问题