Sorting sequential values in an array using JavaScript.Would you like me to

Looking for help with organizing an Array:

var arr = ['a','a','b','b','b','c','d','d','a','a','a'];

I am aiming to achieve the following output:

[
  ['a','a'],
  ['b','b','b'],
  ['c'],
  ['d','d'],
  ['a','a','a'],
]

Note: The goal is to group only sequential repeated values, not all repeated values.

If anyone can assist me with this, I would greatly appreciate it!

Answer №1

A unique solution utilizing the power of Array.prototype.reduce() along with a reference to the previous element.

var arr = ['x', 'x', 'y', 'y', 'z', 'a', 'a', 'b', 'c', 'c', 'd'],
    result = [];

arr.reduce(function (prev, current) {
    if (current !== prev) {
        result.push([]);
    }
    result[result.length - 1].push(current);
    return current;
}, undefined);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Answer №2

If you want to simplify your array, you can use the following approach:

var arr = ['a','a','b','b','b','c','d','d','a','a','a'];

var result = arr.reduce(function(r, i) {
    if (typeof r.last === 'undefined' || r.last !== i) {
        r.last = i;
        r.arr.push([]);
    }
    r.arr[r.arr.length - 1].push(i);
    return r;
}, {arr: []}).arr;

console.log(result);

For more information on how to use Array.prototype.reduce(), check out this link.

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

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

What is the best way to add a new key and value pair to a multi-dimensional array using PHP?

I am dealing with an array that has a specific format. For reference, here is an example Json structure: My task is to include "super_parent_id" in each of the childData arrays. If a childData array exists, I need to add super_parent_id to it. Similarly, ...

Encountering a problem while moving the endpoint's location in Express.js

My journey to learn about REST API and session-based Authentication in express.js took an unexpected turn when I encountered a fascinating error while trying to relocate the endpoints. Upon moving the endpoints, I decided to send a request to the /me endp ...

Exploring the Interaction Between Node.js and a Windows 10 Server on a Local Machine

I am curious about the interaction between Nodejs Server and a local machine. Specifically, I would like to understand how tasks such as: Thread Level CPU Cycle Socket Level IO Any help in clarifying this process would be greatly appreciated. ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

The function within the loop will only execute one time

I am facing an issue with a JavaScript function that is looping through my data. I have another function called inside the loop, but it only executes once on the last index. The code looks like this and I want this function to execute every time. Insid ...

Unable to retrieve elements following jQuerymobile page alteration

To demonstrate the issue I'm facing, I've set up a basic example on my GitHub here: https://github.com/kanesee/jqm-page-state In this scenario, I have a page called page1.html where there is a div with an id of "content" whose color is changed t ...

Guide on incorporating JavaScript code within a PDF document

Looking for guidance on implementing JavaScript in PDF files I am seeking advice from those familiar with adding JavaScript actions to PDF documents, as this is a new area of exploration for me. While I have experience with JavaScript in web development, ...

Adjusting the background color of <tr> depending on the number of <tr> elements in the HTML using CSS

When working on my HTML page, I have utilized multiple <tr> tags with different bgcolor values such as: <tr bgcolor="#000000"> <tr bgcolor="#E5F1CC"> <tr bgcolor="#D30A0A"> <tr bgcolor="#656766"> I am aiming to assign unique ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

Exploring methods to effectively send a large string array back to jQuery

Currently, I am facing an issue with a jQuery/ajax call to my web method which is defined in the code-behind page of my ASP.NET application. The goal is to return a string array containing 2000 items, but unfortunately, I keep encountering an undefined er ...

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

Eliminate the flickering effect on the dropdown menu

Is there a way to eliminate the annoying 'flicker' effect on my menu? Whenever I click on 'Dropdown 1', I notice that Test 1 and Test 2 flicker. My assumption is that this is due to my use of the !important declaration. Any suggestion ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...

"Unlocking the Power: Sending a Complex JSON Object to PHP from the Dojo

Trying to send a complex JSON object to the server using PHP, but encountering difficulties in sending it. Here is the code snippet: Snippet from DOJO: var ObjArry=[]; var test1 = {key:value, key:value, key:value, key:value}; var test2 = {key:value, ...

Measuring Euler Angles with 9-Axis Analog Sensor Data

I am trying to calculate Euler angles using analog sensor data in JavaScript. The sensor data consists of gyro, accelerometer, and magnetometer readings in three dimensions. I find the mathematical aspect a bit challenging, so any assistance or advice woul ...

Order a list based on a specific subsequence

Hey there! I have a collection of file names: "1_EX-P1-H2.3000" "10_EX-P1-H2.3002" "100_EX-P1-H2.3074" "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070" "2_EX-P1-H2.3000" "3_EX-P1-H2.3000&q ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Display a crimson undulating line beneath select words within the input field

I'm currently working on a component in React that involves using an input field to type query syntax, similar to (A=2 and B="Value2"). My goal is to highlight errors by displaying a red wavy line below objects that are incorrect, without affecting th ...