Eliminate adjacent items in an array to avoid duplicates and keep track of the remaining count

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)

Answer №1

UPDATE: The code now groups entries that are close to each other

const array = [
    { output: "testing" },
    { output: "testing" },
    { output: "hello" },
    { output: "world" },
    { output: "world" },
    { output: "testing" }
];

// Result objects
let subRes = false;
const res = [];

// Loop through the array
for(let i = 0; i < array.length; i++) {
  // Create a count object
  if(!subRes) subRes = {
    output: array[i].output,
    count: 1
  }
  // Check if the next entry is the same
  if(array[i+1] && array[i+1].output === array[i].output) {
    subRes.count++;
  } else {
    res.push(subRes);
    subRes = false;
  }
}

// Log the result
console.log(res);

Answer №2

Perform filtering on the given array and then display the output

An illustrative example is provided below

var myArray = [
    {
        value: "apple",
    },
    {
        value: "apple",
    },
    {
        value: "banana",
    },
    {
        value: "orange",
    },
    {
        value: "orange",
    },
    {
        value: "apple",
    },
]

// Utilize reduce method to condense the array into a single object
result = myArray.reduce((acc, val) => {  
  if(val.value === acc.last_val){
    acc.output[acc.output.length - 1].quantity += 1;
  } else {
    acc.output.push({...val, quantity: 1})
  }
  
  acc.last_val = val.value;
  return acc;
}, {output: [], last_val: null});

console.log(result.output);

Answer №3

To make management and reuse easier, consider utilizing the reducer function in JavaScript.

Method 1

const array = [...]

const reduceCount = (acc, obj) => {
  const key = obj["output"];
  // check if we already store the key
  if(!(key in acc)){
    //the key is not register yet, so we create a counter state
    acc[key] = {count: 0};
  }

  //increment the key state counter
  acc[key]['count'] += 1
  
  return acc;
}

// Reduce the array to get state of each key
const dictCount = array.reduce(reduceCount, {});

console.log(dictCount) // { testing: { count: 3 }, hello: { count: 1 }, world: { count: 2 } }

const newArray = Object.keys(dictCount).map(key => ({
  output: key, 
  count: dictCount[key]['count']
}));

console.log(newArray) 

/** output
[
  { output: 'testing', count: 3 },
  { output: 'hello', count: 1 },
  { output: 'world', count: 2 }
]
 */

Method 2: Another Approach for Better Reusability:

const array = [...]

const reduceCount = target => (acc, obj) => {
  const key = obj[target];
  // check if we already store the key
  if(!(key in acc)){
    //the key is not register yet, so we create a counter state
    acc[key] = {count: 0};
  }

  //increment the key state counter
  acc[key]['count'] += 1
  
  return acc;
}

const counterState = target => arr => arr.reduce(reduceCount(target), {});
const counterStateOutput = counterState('output'); //specialize the function

// transform state to array
const stateToArray = state =>  Object.keys(state).map(key => ({
  key,
  count: state[key]["count"]
}));

console.log(stateToArray(counterStateOutput(array))) 
//or
console.log(stateToArray(counterState('output')(array))) 

/** output
[
  { key: 'testing', count: 3 },
  { key: 'hello', count: 1 },
  { key: 'world', count: 2 }
]
 */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

eliminate elements from a PHP array

I have an array of links and another array containing specific values that I want to filter out from the list, for example: Example link 1 Example link 2 Example link 3 ... I am attempting to remove all instances of "http://www.example.com". I have trie ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...

Issue with AngularJS post request yielding status code 304 instead of successfully submitting data to backend server

I've put together a basic form structured like this: Here's the controller code: angular.module('clientApp') .controller('SignupCtrl', function ($scope, $http, $log, alertService, $location, userService) { $scope.si ...

Creating an Angular project that functions as a library and integrating it into a JavaScript project: a step-by-step guide

Is it feasible to create an Angular library and integrate it into a JavaScript project in a similar manner as depicted in the image below? The project structure shows trading-vue.min.js being used as an Angular library. Can this be done this way or is th ...

Utilize dependency injection to connect services with controllers located in separate files

In my storage.js file, I have defined a controller and service as follows: angular.module('app', []). controller('storageController', ['$scope', 'storage', function ($scope, storage) { ...

What is the best way to manage the login notification?

Is there a way to close the alert or input the UserId and password and then click on Login? Here is the code for the alert This is how the alert appears I could use some assistance in managing this alert ...

Alert received upon selecting the React icon button

In the login code below, I have utilized FaEye and FaEyeSlash react icons. However, every time I click on them, a warning message pops up. To avoid this issue, I attempted to switch from using tailwindcss to normal CSS. Login.jsx import { useContext, useS ...

Tips for modifying the JSON array output into an object using PHP

I am encountering an issue with the API JSON output. I am experiencing some difficulties with the JSON output when it comes to looping through, as it seems to create its own indexes despite my attempts to force the array format into an indexed array. Here ...

How to correctly initialize character arrays in Objective-C?

Struggling to successfully copy the value of a char [] array to another. Whenever I attempt, I seem to fail. The following format works: char array[] = { 0x00, 0x00, 0x00 } However, the issue arises when I try: char array[] = char new_array[]; Regardl ...

What is the most effective way to retrieve data when a user clicks?

I am currently working on creating a menu that showcases three different categories: Streaming, On Tv, and In Theaters. This is inspired by the layout found on The initial data displayed belongs to the Streaming section, which is being fetched via JSON fr ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Dynamically adding items in a row to a form panel using extjs

While using ExtJS 3.4, I faced a challenge with laying out three buttons in a row within a formpanel. After some research, I discovered that nesting item blocks might be the correct approach. Below is the code snippet showcasing what I have implemented: v ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

Ways to emphasize a specific row within a table for special occasions

I have limited knowledge of CSS and JavaScript, but I am looking for a way to create a notification highlight that functions similarly to when someone comments on a Facebook post. When clicked, it should direct me to the specific comment with a temporary h ...

How to set an already existing anonymous object to a property within the data property in VueJS

Help needed for a beginner question let myOptions: { chart: { height: 350, type: 'bar' }, colors: ["#800000"] }; let vueExample = new Vue({ el: '#example', components: { apexchart: VueApexCh ...