Arranging based on the initial elements of the array

Could I please receive the arrangement ['H','H','A','A'] from the given input ['H','A','H','A']

Is there a way to organize it according to the first occurrence of each character?

Answer №1

If you're looking to organize an array based on groupings, one approach is to utilize sorting with a mapping technique. By creating a temporary object with a hashtable for tracking group counters, you can effectively sort the elements based on their respective groups.

The sorting process is specifically tied to the groupings within the array.

Once sorted, the result is then mapped according to the index of the rearranged temporary array.

var array = ['H', 'A', 'H', 'A'],
    groups = Object.create(null),
    counter = 0,
    result = array
        .map((v, index) => ({ index, group: groups[v] = groups[v] || ++counter }))
        .sort((a, b) => a.group - b.group)
        .map(o => array[o.index]);

console.log(result);

A similar concept can be achieved using a Map to maintain the order of the first occurrences.

var array = ['H', 'A', 'H', 'A'],
    map = new Map;

array.forEach(v => map.has(v) || map.set(v, map.size + 1));

array.sort((a, b) => map.get(a) - map.get(b));

console.log(array);

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

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

Initiate an AJAX call with various data formats included

I am currently developing an application that allows users to input values through an interface and send AJAX requests (similar to a REST API). My question pertains to sending data of multiple types in a single request. For example, here is a scenario: F ...

Programmatically arranging View outcomes – is it possible?

I have successfully obtained the results of a view using the function views_get_view_result(). Now, I need to sort the array in a way that is not possible within the Views interface. I have managed to store all the necessary data in a $rows variable. Howe ...

Show a directional indicator on hover in the date selection tool

I am currently using a datepicker that looks like this: https://i.sstatic.net/XsrTO.png When I hover over it, three arrows appear to change days or show the calendar. However, I would like to remove these arrows. Here is the code snippet: link: functi ...

Angular JS causing text alignment issues in table cells when viewed on mobile devices

I have created a web application that requires both desktop and mobile views, utilizing Angular JS. Everything is functioning as expected except for the text alignment within tables. I attempted using <td align="left">, but it did not produce any cha ...

Having trouble modifying a value in a form and submitting it to the following jsp page

I'm encountering an issue with changing the value in a hidden input element before submitting data to another JSP file (db.jsp) for processing. The value should be different depending on which button is clicked, but it always remains as the default va ...

What is the outcome of XmlHttpRequest.responseText?

I am new to JavaScript and looking to explore the potential of XMLHttpRequest.responseText with a specified URL. Can someone guide me on how to efficiently test this? let url = "http://m.google.com/"; <br> let xmlHttp = new XMLHttpRequest(); <br& ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

How should a JavaScript object be properly formatted?

Recently, I created a project using ng-repeat with AngularJS 1.x, and it was smooth sailing. JavaScript: var app = angular.module('myModule', []); app.controller('myController', function() { this.dishes = [ { 'name&a ...

Determining the smallest bounding box of an object within a camera image using Three.js

Looking to analyze and outline the minimum bounding rectangle (MBR) of an object captured by a camera in a 2D projection. In the image below, you can see the MBR of a cube object. I manually sketched the MBR (red rectangle) based on visual estimation. Is t ...

Exploring JSON array handling with jquery

Here is the JSON data I am working with: { "category": { "category_identification": "1", "category_name": "C1", "image_one": "1.PNG", "image_two": "1_.PNG", "logo": "LOGO_1.PNG", "category_description": "DESCRIPTION" }, "responseCo ...

When exporting an enum in StencilJS with TypeScript, the error "Cannot find name..." may occur

Looking for a solution: https://github.com/napolev/stencil-cannot-find-name In this project, there are two main files to consider: custom-container.tsx import { Component, Element, State } from '@stencil/core'; @Component({ tag: 'cu ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...

Combining arrays based on duplicate key values

I have an array that I need to convert into a sub-array with multiple unique keys. Using the `array_merge_recursive` function has not worked for me as I have multiple arrays in a loop, and this function only works with 2 or 3 arrays. Array ( [0] => ...

The Google Apps spreadsheet script occasionally fails to complete iteration but functions properly in all other aspects

I have a script that goes through a spreadsheet of student data one row at a time to email students and their parents if the student's grade is below 60. The spreadsheet columns include: Student ID, Name, Email Address, Parent's Email Address, an ...

What steps can I take to modify the peeking effect from hover to scrolling?

I have successfully integrated a peeking effect on my website. Check it out here: http://jsfiddle.net/7yrWL/1/ Currently, the effect triggers when I hover over the image. What I want now is for the peeking effect to only activate when the user scrolls to t ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...