javascript - 在数组上增加对象属性,如果在 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;
}
}
}
解决方案
推荐阅读
- batch-file - 将 bat 中的标题行插入 csv 文件
- api - 使用 netsh 在设备上为 API 添加 ssl 证书
- pandas - 对熊猫数据框中的行进行编号
- php - 404 未找到错误,无法重定向到另一个页面/视图
- javascript - javascript 扫雷问题,显示点击的 0 磁贴周围的磁贴
- python - 为什么 tkinter Label 对象中没有引用照片图像?
- r - 如何编写一个函数来检测 R 中是否存在对象,如果不存在,则读取该名称的文件?
- php - 警告:在发布新闻块中为 foreach() 提供的参数无效
- java - 将 Employee 的 ID 值获取到另一个 Entity 类中
- javascript - 如何正确使用 mysqljs 查询?