Arrange an array containing duplicate elements by prioritizing the first instances

I have a unique array of items that are duplicated, occurring twice right next to each other, such as:

const arr = ['1', '1', '2', '2', '3', '3']

My goal is to rearrange the array so that all unique values come first followed by their duplicates, like this:

const arr = ['1', '2', '3', '1', '2', '3']

Is there a way to achieve this using the sort() function or should I explore other methods?

I attempted the following approach but it did not yield the desired results:

const sorted = myDublicatedArray.sort((left, right) => left.index - right.index);

Answer №1

When tackling this problem using Array.sort() alone, it can present challenges. However, the following approach should be effective for handling both numeric and string inputs, unless specific requirements dictate otherwise:

const arrayWithDuplicates = ['1', '1', '2', '2', '3', '3'];
// convert to a Set to obtain unique values
const uniqueValues = new Set(arrayWithDuplicates);
// sort by value
const sortedArray = Array.from(uniqueValues).sort((a, b) => a - b);
// create a duplicate of the sorted array
const arrayOrganized = [...sortedArray].concat(sortedArray);

console.log(arrayOrganized)

Answer №2

Based on the feedback received, it seems that there will be consecutive pairs of duplicate values in the input array. This means there will never be 3 or more duplicates in a row. To handle this scenario, you can utilize the following mapping technique:

const arrayWithDuplicates = ['1', '1', '2', '2', '3', '3'];
const result = arrayWithDuplicates.map((_, i, a) => a[i * 2 % a.length]);
console.log(result);

If speed is crucial for your implementation, consider using a traditional for loop approach:

const arr = ['1', '1', '2', '2', '3', '3'];
const result = [];
for (let j = 0; j < 2; j++)
    for (let i = 0; i < arr.length; i += 2)
        result.push(arr[i]);
console.log(result);

Answer №3

To achieve this, you can create an index for each value and then transform it into a grouped array followed by a flat array as the final output.

const
    array = ['1', '1', '2', '2', '3', '3'],
    result = array
        .reduce((indices => (r, v) => {
            indices[v] ??= 0;
            (r[indices[v]++] ??= []).push(v);
            return r;
        })({}), [])
        .flat();

console.log(result);

Answer №4

To achieve this, you can utilize the sort method in JavaScript. Begin by converting the elements into pairs of [element, occurrence]. For instance, the initial occurrence of 2 is represented as [2,0].

Subsequently, arrange the pairs first based on their occurrences, and in case of equal occurrences, sort them based on the element itself.

Lastly, extract only the element from each [element, occurrence] pair.

const arr = ['1', '1', '2', '2', '3', '3']

const result = Object.values(Object.groupBy(arr, e => e))
  .flatMap(arr => arr.map((e,i) => [e,i]))
  .sort(([a,i], [b,j]) => i-j || a-b)
  .map(([e]) => e)

console.log(result)

Answer №5

If the values are in ascending order and come in pairs, you can utilize the following method:

const arr = ['1', '1', '2', '2', '3', '3'];
const uniq = new Set(arr);
const desired = Array.from({ length: 2 }).flatMap(() => Array.from(uniq));

console.log(desired);

The code snippet above initializes a Set named uniq, containing all unique elements from the array. To achieve the desired outcome, we generate an array of length 2 using Array.from() and then expand it with flatMap(). By converting uniq from a Set to an array, we maintain the item sequence based on insertion order ('1'</​, followed by '2'</​, and finally '3'</​).

In scenarios where the number of duplicates may vary dynamically (consistently across the entire array), you can enhance flexibility by incorporating

Array.from({ length: arr.length / uniq.size })
. This approach facilitates inputs like the ones shown below:

const arr = ['1', '2', '3'];
const arr = ['1', '1', '1', '2', '2', '2', '3', '3', '3'];

Note that the data elements should still be sorted and exhibit uniformity in duplicate quantity.

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

When an input in Vue.js registers a @keyup event, it will return to the parent

I am encountering an issue with my input component where pressing enter redirects me to the parent component. Even adding a @keyup event does not solve the problem. Could this be happening because I am in a child component? How can I prevent the enter key ...

Activating a inaccessible element

Attempting to enable a disabled element upon clicking a P element, the following code snippet demonstrates storing a value from one textbox into another. The appended div contains a subsequent textbox which will be disabled. On mouseover of the div, option ...

Incorrect behavior of responsive background images

For the first time, I am working on a school project that requires me to create a responsive website. I am following the "mobile first" approach. On stackoverflow, I came across a helpful way of making background images responsive: background-image: url(. ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Understanding the fundamental concepts of callbacks with Backbone.js

Currently, I am working with Backbone to send a login form to my server. Once the form is submitted and the database query is successful, a boolean value is flipped to enable GET responses from the server. However, the issue arises when it attempts to fetc ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

Javascript did not provide any prompt

I can't seem to get the function to run when I click the link, it only takes me to the link address. (The final alert() function is not executing). I really need that alert message, what am I missing? Below is my code: <html> <head> ...

Use YUI to parse JSON data enclosed in square brackets and curly braces within a packet

Recently, I have been diving into the world of JSON, JavaScript, and YUI while working on a homework assignment. The JSON packet I am dealing with has the following structure: [{"id":"1234", "name":"some description","description":"url":"www.sd.com"}, {sa ...

Sending an AJAX request with an unpredictable quantity of parameters

I built a form for my website that pulls questions from a database based on certain variables. This means the number of questions available is unknown. The code snippet for displaying these questions looks like this: HTML <ol class="questions"> ...

Submit a form to the same page without reloading and toggle the visibility of a div after submission

Is there a way to submit a form without refreshing the page and hiding the current div while showing a hidden one? I attempted to use the following code, but it ends up submitting the form and reloading the page. <form method="post" name="searchfrm" a ...

Trigger javascript function after clicking on two buttons

I am currently working on developing a web game inspired by Duolingo. In a specific scenario, I need a function to be triggered after two button clicks to progress further. However, I am facing challenges in finding solutions online or understanding it on ...

Scroll horizontally based on mouse movement

My angular directive that enables me to choose the content of table cells is performing as expected. However, I encountered an issue when attempting to select multiple cells at once - the scrollbar does not move, hindering my ability to select the cells. ...

Unable to retrieve parameter while making a POST request

Need some help with attribute routing. I'm having trouble getting parameters from the HTTP body. The ConnectionID Class includes a property named CValue. $('#btn').click(function () { $.ajax({ type: "POST", url: "http:// ...

What are the advantages of going the extra mile to ensure cross-browser compatibility?

It's fascinating how much effort is required to ensure web applications work seamlessly across all browsers. Despite global standards like those set by W3C, the development and testing process can be quite laborious. I'm curious why all browsers ...

When attempting to select an option from the dropdown menu, I encounter an issue where the

My code is not behaving as expected. Whenever I click on the child elements, the dropdown changes to display: none. I am encountering an error when clicking on the input frame and displaying:none. How can I resolve this issue? I would like to be able to ...

Obtaining Navigation Parameters within Custom React Navigation Title

In the React Navigation StackNavigator, I created a custom title that looks like this: const CustomStackNavigator = StackNavigator({ Home: { screen: HomeScreen } }, { navigationOptions: { headerTitle: <GradientHeader title={this.props.nav ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

The Listbox fails to add an item to its list when the selection is set to None

I have been utilizing an array to fill my listbox with data. It was functioning properly until I used the listbox.selection.none function (to prevent any items from being selected). After implementing this, the listbox only adds new values to its first i ...

What are some best practices for managing asynchronous requests on the client side with Node.js?

I am a beginner in NodeJS, currently utilizing it on the server side for my projects. My goal is to create a simple REST-based GET request that takes a search parameter called searchvar from the user and returns any matching records found in a JSON array. ...

Methods for removing a CSS element that specifically targets a table using JavaScript

I am facing an issue with my Drupal site where the CSS for a Google Org Chart is being overridden by some existing styles. Below is the code snippet in question. The CSS I need to eliminate: .MainBlock table td { border-right: 1px solid #045273; bo ...