Sorting an array by item type involves prioritizing strings first, followed by floats and integers, while maintaining the original order of each type without utilizing additional arrays

Input:

[2,"x","y",7, 0.5, "z", 0.9, 3, 4, "a", "d", 0.1, 6.5, 12, 56,"c","m",0.3 ,"p", "q", 8, 9]

Output:

["x", "y", "z", "a", "d", "c", "m", "p", "q", 0.5, 0.9, 0.3, 6.5, 0.1, 9, 7, 3, 4, 12, 56, 8, 9]

function sorter(arr) {
    var arr1, arr2, arr3;
    arr1 = [];
    arr2 = [];
    arr3 = [];
    for (var i = 0; i < arr.length; i++) {
        if (typeof arr[i] === "string") {
            arr1.push(arr[i]);
        } else if (typeof arr[i] === 'number' && !isNaN(arr[i])) {
            if (Number.isInteger(arr[i])) {
                arr3.push(arr[i]);
            } else {
                arr2.push(arr[i]);
            }
        }
    }
    return [...arr1, ...arr2, ...arr3];
}

Answer №1

Implementing a strategy using a single sort comparator function ...

function orderByItemTypeOnly(a, b) {
  const precedences = {
    'string': 1,
    'float': 2,
    'int': 3,
  };
  const getType = val =>
    ((typeof val === 'number') && Number.isFinite(val))
      ? Number.isInteger(val) && 'int' || 'float'
      : (typeof val);

  const aType = getType(a);
  const bType = getType(b);

  return (
    (precedences[aType] || 4) - (precedences[bType] || 4)
  );
}

console.log([

  7, "a", "b", 5, 0.1, "c", 0.5, 9, 1, "e", "m",
  0.3, 8.5, 74, 89, "f", "r", 0.5, "x", "y", 4, 7

].sort(orderByItemTypeOnly));
.as-console-wrapper { min-height: 100%!important; top: 0; }

Another way to tackle this problem is by utilizing a method other than sort, such as employing a reduce approach ...

function collectAndShiftItemByType(list, item, idx, arr) {
  if (list.length === 0) {
    list.push([], [], [], []);
  }
  const typeListIndex = ((typeof item === 'number') && Number.isFinite(item))
    ? (Number.isInteger(item) && 2 || 1)
    : (typeof item === 'string') ? 0 : 3;

  // categorize into sub lists ... [0]string, [1]float, [2]integers, [3]unknown.
  list[typeListIndex].push(item);

  if (idx >= arr.length - 1) {
    list = list[0]
      .concat(list[1])
      .concat(list[2])
      .concat(list[3]);
  }
  return list;
}

console.log([

  7, "a", "b", 5, 0.1, "c", 0.5, 9, 1, "e", "m",
  0.3, 8.5, 74, 89, "f", "r", 0.5, "x", "y", 4, 7

].reduce(collectAndShiftItemByType, []));
.as-console-wrapper { min-height: 100%!important; top: 0; }

Answer №2

Utilize the sort() method with a custom comparison function that prioritizes types over values.

function typeSorter(arr) {
  function typePriority(val) {
    const types = ["string", "float", "integer"];
    let type;
    if (typeof val === "string") {
      type = "string";
    } else if (typeof val === "number" && Number.isInteger(val)) {
      type = "integer";
    } else if (typeof val === "number" && !isNaN(val)) {
      type = "float";
    }
    return types.indexOf(type);
  }

  return arr.sort((a, b) => typePriority(a) - typePriority(b));
}

console.log(typeSorter([7,"a","b",5, 0.1, "c", 0.5, 9, 1, "e", "m", 0.3, 8.5, 74, 89,"f","r",0.5 ,"x", "y", 4, 7]));

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

Activate search bar by clicking on it

I am currently attempting a basic jQuery example to expand a search bar on mouse click, but for some reason, my code is not working as expected. I have a simple jQuery function to display the input field when the button with the class "expand" is clicked, ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...

I need some help with adjusting the number of rows shown per page in MaterialReactTable

I've been utilizing MaterialReactTable and my goal is to display only 5 items on each pagination page. Despite setting muiTablePaginationProps, I still see 10 items per page. How can I resolve this issue? <MaterialReactTable columns={columns} ...

Displaying and Concealing Messages with VueJS

Currently, I have set up a basic CLI structure environment and created a component that displays messages/alerts such as "Login Failed." Since this component is intended to be reused throughout the entire app, I decided to import it into the root App.vue f ...

Are there any specific steps I should take to ensure that my server can support jQuery.getJSON when using a bookmarklet?

Currently, I am in the process of creating a bookmarklet that will require some user details to be input. After researching my options for cross domain communication, I have found that my best choices are either using jQuery.getJSON or adding a form and i ...

Tips for Making Your Popup Window Stand Out

Looking to design a unique pop-up window featuring three tree-style radio buttons and a single submit button. Upon selecting one of the radio buttons, the chosen value should be recorded in the parent window. ...

Font family 'anticon' is not recognized

While following a coding tutorial on YouTube, I encountered an error message that has me stumped. Despite having the correct import statement and dependency installed, the issue persists. Error message in iOS simulator: https://i.stack.imgur.com/LOVCQl. ...

Halt spread: descend in a bubble?

It seems that the issue at hand may not be related to propagation, but rather a design flaw. I have come across information suggesting that propagation problems tend to bubble up, however, let me explain my situation. I am working with a table edit grid. ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...

"Learn the steps to seamlessly add text at the current cursor position with the angular-editor tool

How can I display the selected value from a dropdown in a text box at the current cursor position? I am currently using the following code: enter code selectChangeHandler(event: any) { this.selectedID = event.target.value; // console.log("this.selecte ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

What is the process of combining two identical objects in Angular JS?

Is it possible to merge and sort two objects in Angular JS that have the same fields, notifications.fb and notifications.tw, based on their time field? ...

Utilize the conditional GET method when including scripts through tags in an HTML webpage

Is it possible to benefit from HTTP conditional requests when including a script in the head section of a page? My goal is to cache dynamically downloaded JavaScript files that are added to the head section using script tags. If this approach isn't fe ...

The calendar loses its focus when I try to interact with it

One issue I have encountered is that when I click on the input field to display the Calendar component, and then click outside of it to hide it, everything works smoothly. However, the problem arises when I click directly on the icon (Calendar component) i ...

Creating a duplicate of a Flex object in HTML without the need to reinitialize

I'm currently developing a flash object that involves processing a large number of images. My goal is to load multiple flash objects on the same page in order to capture an image, make adjustments, and then display it within each flash object. Howeve ...

Show JSON response using AJAX jQuery

After receiving the JSON Response, { "user_data": { "id": 22, "first_name": xxx, "last_name": xxx, "phone_number": "123456789", }, "question_with_answers" : [ { "id": 1, ...