I'm currently working on developing a console interface similar to those found in web browsers. However, I've hit a roadblock when it comes to handling duplicate messages. For example, if you input
[...Array(10)].map(x => console.log("hello"))
into the console, it will output (10) hello
.
Now, let's say I have the following array:
const array = [
{
output: "testing",
},
{
output: "testing",
},
{
output: "hello",
},
{
output: "world",
},
{
output: "world",
},
{
output: "testing",
},
]
The desired output should resemble this:
(2) testing
hello
(2) world
testing
So, what I want to achieve is removing consecutive duplicates and displaying how many times they occur in a row. The modified output should be structured like this:
const newArray = [
{
output: "testing",
count: 2
},
{
output: "hello",
count: 1
},
{
output: "world",
count: 2
},
{
output: "testing",
count: 1
},
]
One approach I considered involves utilizing the following code snippet:
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 > 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)