I am interested in tallying up the number of adjacent matching elements within an array and then providing the final count

I have an array and want to find all neighboring matches, count them, and then return the count. This needs to be done in a loop using .map() so that I don't need to store memory of what was counted beyond the current element. The number of current elements will be used to reserve enough spaces for each group of elements.

array = [ball, batter, batter, amount, amount, github, github, github, account, account, account, account, account, account, account, github, github, github]

An example of the desired results from this array would be: on the first loop it would return 1, second loop would return 2, then 2, then 3, then 7, then 3

This count will serve as a variable to reserve space like so:

number to reserve: count

Through each loop, the variable count will be updated with the current elements count. The counting loop will not stop until the next element does not match the current element, and the variable count will only be available once all consecutive matches are found. Therefore, if I put console.log(count) at the end of the function, I would get each number output individually.

Answer №1

To easily determine the consecutive strings in an array, you can follow this method:

const array = ["ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"]

const result = [];
let last = array[0], lastSameIndex = 0;
for (let i = 1; i < array.length; ++i) {
  if (array[i] !== last) {
    result.push(i - lastSameIndex);
    lastSameIndex = i;
    last = array[i];
  }
}
result.push(array.length - lastSameIndex);

console.log(result);


Let's start with some initial values such as

last = array[0], which means last = "ball", and lastSameIndex = 0

We will begin from index 1 and focus on a scenario where two elements are not equal i.e. array[i] !== last. In such cases, we need to add the count of the same element encountered so far like this:

result.push(i - lastSameIndex);

After that, update the value and index to mark the new element that needs to be counted again.

lastSameIndex = i;
last = array[i];

Additionally, handling the case when the loop reaches its end is important. Here, we push the count of the last element that was being counted from the start or lastSameIndex until the end of the array.

result.push(array.length - lastSameIndex);

Second approach

const array = [ "ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"];

let lastStr = "",
  num = 0;
const result = array
  .map((s) => {
    if (lastStr !== s) {
      lastStr = s;
      num = num === 0 ? 1 : 0;
    }
    return num;
  })
  .join("")
  .match(/(\d)\1*/g)
  .map((s) => s.length);
  
console.log(result);

Answer №2

As you iterate through each item, check if it is different from the previous one - if so, insert 1; otherwise, increment the last number in the array by 1.

const items = ["ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"]

const results = [];

items.forEach((item, i) => {
    if (items[i - 1] !== item) return results.push(1);

    const last = results.length - 1;
    results[last] = results[last] + 1;
});

console.log(results);

Answer №3

  • Combine the elements of an array into a string separated by commas using the method array.join(","):
    ball,batter,batter,amount,amount,github,github,github
  • Utilize regular expressions (regex) with pattern /([a-z]+,)\1*/gi to identify repeated words and get:
    ['ball,', 'batter,batter,', 'amount,amount,', 'github,github,github,...]
  • Determine the number of words in each string of the array by applying s.split(',').length-1

JavaScript Code:

array.join(",").match(/([a-z]+,)\1*/gi).map((s) => `${s.split(',').length-1}`);

Outcome: ['1', '2', '2', '3', '7', '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

Issue with Loading JQuery AutoComplete

Issue with Code Javascript Code using Jquery: $('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) { location.href = item.AGE; }); Json Data: ...

Validation of New Relic License Key

Is there a way to verify the validity of a provided New Relic license key in a JavaScript application? I have searched through the documentation but did not come across any API endpoint for this purpose. UPDATE: Just to clarify, we do not have access to ...

Ways to combine all similar key values into an array

Apologies if the question seems unclear. Essentially, I am dealing with an object structured as follows: [{"6":6.5},{"4":4.2},{"6":6.3}] My goal is to eliminate duplicate keys while preserving their values, and merge them into a single unique key, formin ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

"Caution: Refs cannot be assigned to function components" message encountered when utilizing a custom component in Next.js

I created a component called HeaderIcon with the following code: function HeaderIcon({ inactiveIcon, activeIcon }) { const [isActive, setIsActive] = useState(false); return ( <div onClick={() => setIsActive(!isActive)}> {isActive ? ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Error: Cannot access the 'top' property of an undefined object

Here is a snippet of my jQuery code: $(document).ready(function(){ $('.content-nav a').on('click',function(){ var str = $(this).attr("href"); var the_id = str.substr(1); $("#container").animate({ scrollTop: $ ...

Users are encountering timeout issues when attempting to connect to the Azure Postgres flexible database through the node.js server deployed on the Azure App Service

My node.js express server is deployed on Azure App Services, connecting to an Azure flexible Postgresql database. Strangely, everything works fine when running the server locally, but once it's deployed to Azure App Service, all requests time out: htt ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

Slicing an array in Javascript/Angular before it is officially initialized

Is it possible to specify the portion of an array to retrieve before making a $http GET request in Angular? I am aware of slicing arrays, but wondering if I can set this up in advance for better performance. In PHP, you can do something similar, but not ...

Random Label Selector in Visual Basic code

Greetings! I am currently working with Visual Basic in Visual Studio Express 2013 and facing a challenge. My goal is to develop a function that can extract a list of first names from a text file and store each name in an index within an array. However, ins ...

What is the process for loading the chosen option JSON object from an array when a button is clicked?

I have a TypeScript file containing JSON objects that can be selected as options from a dropdown list. I am looking for guidance on how to load/instantiate the selected JSON object when the user clicks a button to proceed. Specifically, I would like to le ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

Struggling to identify every occurrence of a specific character (provided by the user) within a character array (also provided by the user) in the C

Being a first-year student, I am still grappling with the intricacies of the C language. One of my assignments requires me to create a program where a user inputs a word and a letter. The program then finds all the positions of that letter in the word. Fo ...

Unable to assign values to objects in a C# array

class City { string name; public string getName() { return name; } public void setName(String value) { name = value; } } static void Main(string[] args) { City[] arr = new City[1]; arr[0].setName("New ...

Error: Unable to access the 'center' property of an undefined value in the three.module.js file

I started delving into coding a few months back, with my focus on mastering three.js/react. Currently, I am engrossed in a tutorial located at [https://redstapler.co/three-js-realistic-rain-tutorial/], where I aim to create a lifelike rain background. The ...

Retrieve value from array input

Is there a way to extract input text values from an array using JavaScript? Here is the code snippet: Item : <input id="t_item" name="t_item[]" type="text" class="teks3"> Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3"> &l ...

Use the filter method to organize arrays into subarrays based on their length, filtering out those with a length greater than or

Hey there, I've been working on incorporating the array filter property to separate subarrays that are greater than and less than 3 into two distinct functions. Unfortunately, I'm a bit stuck on how to continue fixing my functions. Can someone pr ...

Using JavaScript to interact with text elements in external SVG documents

When it comes to creating an SVG within HTML and assigning specific IDs to text elements for easy access, everything works smoothly. For example, I can easily retrieve the ID using: let callQSO = document.getElementById("QSOcall").value; and th ...