【发布时间】:2020-08-14 20:18:30
【问题描述】:
我正在尝试制作一个类似于浏览器中的控制台,但卡在显示重复消息上
假设我得到了这个数组:
const array = [
{
output: "testing",
},
{
output: "testing",
},
{
output: "hello",
},
{
output: "world",
},
{
output: "world",
},
{
output: "testing",
},
]
所需的输出如下所示:
(2)testing
hello
(2)world
testing
如果重复消息彼此相邻,我如何删除它们并添加一个计数器来显示行中有多少重复消息。输出应该是这样的
const newArray = [
{
output: "testing",
count: 2
},
{
output: "hello",
count: 1
},
{
output: "world",
count: 2
},
{
output: "testing",
count: 1
},
]
我认为可能是这样的
const array = [{
output: "testing",
},
{
output: "testing",
},
{
output: "hello",
},
{
output: "world",
},
{
output: "world",
},
{
output: "testing",
},
]
let newArray = [];
for (let i = 0; i < array.length; i++) {
if (newArray.length.length > 1 && array[i].output == newArray[newArray.length - 1].output) {
newArray[newArray.length - 1].counter += 1
} else {
newArray.push({
output: array[i].output,
counter: 0
})
}
}
console.log(newArray)
【问题讨论】:
-
你尝试了什么?
-
@Mitya 我的更新不好,无法解决这个简单的问题有点沮丧,呵呵
标签: javascript arrays