首页 > 解决方案 > 在数组上增加对象属性,如果在 javascript 中找到则删除

问题描述

让我们假设我有一个由这些属性定义的对象:

interface HeaderObject {
  height: number;
  title: string;
  length: number;
}

我有一个包含大量 HeaderObject 的数组。

我的目标是对于每个元素,如果给定索引处的元素等于在该索引之前找到的元素,则使其长度增加一并删除当前索引处的对象。

我必须遵循这个规则:如果对象标题等于在索引循环之前找到的第一个(在下面的示例中,如果我在索引 6 中,找到的第一个是索引 0)并且高度等于:我必须检查在找到的索引 (0) 和当前索引 (6) 之间,这些索引之间的所有对象高度是否遵循每个元素的模式 (maxHeight - 1)。

在这里,长度不会更新,因为在高度 2 处,在索引 6 之前,标题不等于:

0: {height: 2, title: "Alpine Skiing", length: 1}
1: {height: 1, title: "2002", length: 1}
2: {height: 0, title: "Gold", length: 1}
3: {height: 2, title: "Archery", length: 1}
4: {height: 1, title: "2000", length: 1}
5: {height: 0, title: "Gold", length: 1}
6: {height: 2, title: "Alpine Skiing", length: 1}

但在这个例子中:

0: {height: 0, title: "Country", length: 1}
1: {height: 0, title: "Athlete", length: 1}
2: {height: 2, title: "Alpine Skiing", length: 1}
3: {height: 1, title: "2002", length: 1}
4: {height: 0, title: "Gold", length: 1}
5: {height: 2, title: "Archery", length: 1}
6: {height: 1, title: "2000", length: 1}
7: {height: 0, title: "Gold", length: 1}
8: {height: 2, title: "Alpine Skiing", length: 1}
9: {height: 1, title: "2002", length: 1}
10: {height: 0, title: "Silver", length: 1}
11: {height: 2, title: "Alpine Skiing", length: 1}
12: {height: 1, title: "2006", length: 1}
13: {height: 0, title: "Gold", length: 1}
14: {height: 2, title: "Alpine Skiing", length: 1}

肯定是 :

0: {height: 0, title: "Country", length: 1}
1: {height: 0, title: "Athlete", length: 1}
2: {height: 2, title: "Alpine Skiing", length: 1}
3: {height: 1, title: "2002", length: 1}
4: {height: 0, title: "Gold", length: 1}
5: {height: 2, title: "Archery", length: 1}
6: {height: 1, title: "2000", length: 1}
7: {height: 0, title: "Gold", length: 1}
8: {height: 2, title: "Alpine Skiing", length: 3}
9: {height: 1, title: "2002", length: 1}
10: {height: 0, title: "Silver", length: 1}
11: {height: 1, title: "2006", length: 1}
12: {height: 0, title: "Gold", length: 1}

提前感谢您的帮助。这是我现在的位置:

for (let j = maxHeight; j <= this.headers.length; j++) {

  for (let k = 1; k <= maxHeight + 1; k++) {
     if (typeof this.headers[j - k] !== 'undefined' && this.headers[j - k].title === this.headers[j].title) {
           this.headers[j - k].length++;
           this.headers.splice(j, 1);
           break;
      }
   }
}

标签: javascriptarraysalgorithm

解决方案


推荐阅读