Organize a collection of strings by sorting them according to a specific character within each string

I am attempting to arrange an array of strings based on a character within each string. Here is what I have so far:

function sortStrings(s) {

  let arr = s.split(' ');
  let letterArr = [];
  let sortedArr = [];
  let n = 0;
  for (var i = 0; i < arr.length; i++) {

    n = arr[i].indexOf(arr[i].match(/[a-z]/i));
    letterArr.push(arr[i][n]);

  }
  letterArr.sort();

  console.log(letterArr);

  for (i = 0; i < arr.length; i++) {
    for (var j = 0; j <= arr[i].length; j++) {

      if (arr[i].indexOf(letterArr[j]) > -1) {
        sortedArr.unshift(arr[i]);
      }

    }
  }
  console.log(sortedArr);
}

sortStrings("24z6 1x23 y369 89a 900b");

The issue arises when I display this array. If I utilize sortedArr.push(arr[i]);, then the outcome is:

["24z6", "1x23", "y369", "89a", "900b"]

However, if I use sortedArr.unshift(arr[i]);, I obtain:

["900b", "89a", "y369", "1x23", "24z6"]

I am puzzled as to why the b comes before the a.

All I want is the sorting to be from a-z. When I tried push() it is correct but reversed (z-a). Using unshift() gives me the correct order except that the b and a are interchanged.

Answer №1

function calculateWords(s) {
   return s.split(' ').sort(function (a,b) {
      return a.match(/[a-z]/i)[0].localeCompare(b.match(/[a-z]/i)[0])})
}

console.log(calculateWords("24z6 1x23 y369 89a 900b"));

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

Prevent form submission when email is missing

function validateEmail(){ var TCode = document.getElementById('email').value; if(TCode.length==0) { email_info.innerHTML="This field is required"; return false; } email_info.innerHTML=" "; ...

How can you convert a string to a boolean in Javascript?

Any tips on converting the options.isdedicated to a boolean value of true or false rather than a string? <?php $isdedicated = file_get_contents("/home/www/html/config.ini"); //echoed true?> <script> var options = []; options.isdedicated ...

When trying to extract information from a v-for loop and pass it into a method, I keep

After sending an array of data objects into a child component via props, I proceeded to use a v-for loop to display the elements exactly how I intended: <div class="col-md-3" v-for="product in products" :key="product.id" v ...

The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view> Routing Configuration app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { t ...

What is the process of redefining the toString method for a function?

I am currently tackling a coding challenge that involves chaining functions. While researching possible solutions online, I noticed that many of them involved using function.toString and overriding the toString method of a function to create a chained add ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

What is the best way to utilize the forEach method in React to manipulate a navigation element containing multiple links?

Here is the code I'm trying to convert: document.addEventListener("scroll", function() { const links = document.querySelectorAll(".nav-link"); for (const l of links) l.classList.toggle('scrolling', window.scrollY &g ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Navigating between socket.io and express using while loops

Currently, I am running an express app with socket.io on my raspberry pi to control an LED panel. The panel is being driven by a while loop that updates the pixels. However, I am looking for a way to modify the parameters of this loop or even switch to a d ...

Finding the dynamic width of a div using JavaScript

I have two divs named demo1 and demo2. I want the width of demo2 to automatically adjust when I drag demo1 left to right or right to left. <div class="wrapper"> <div class="demo"></div> <div class="demo2"&g ...

What advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches: Approach A. Creating app module Using a service to store model data Implementing a controller to retrieve data from the service File 1: Users.js: angular.module('users', []); File 2: userService.js: angular ...

Accessing CouchDB using AngularJS requires users to sign in, with the authentication cookie only being sent to the `/_

Check out my previous posts on this topic here: 1, 2 I currently have an AngularJS app with two controllers. The first one interacts with CouchDB documents, while the second handles sign-in requests to example.com/demo/_session. Upon opening the applicat ...

How can I inject an isolated scope object into an Angular custom directive template?

Having trouble using an object in an angular template within a custom directive. Take a look at this plunker to see the issue I'm facing. After some experimentation, I realized that I need to utilize scope: {address: '='} to pass an object ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

Emails not being sent by Nodemailer, showing a message of 'Message sent: Undefined'

Initially, everything was working fine but suddenly it stopped. I tried sending some emails and then it just stopped with an error message "Message sent: Undefined". Additionally, I encountered the following error message - (node:9048) UnhandledPromiseReje ...

The Growth of Integer Array

Curious about how to dynamically expand an integer array in C? I recently learned about malloc, realloc, and sizeof but could use a bit more guidance on how they function. Could someone provide a simple example of how to achieve this in C? ...

Duplicating Javascript object containing private member

I've searched high and low without finding a solution. Why is it so difficult to clone a javascript object with private members without causing them to become quantum entangled? Take a look at this code... It's a simple private property with get ...

"Deleting a specific row from a SQL Server using Node.js: Step-by-Step Guide

Currently, my setup involves using nodeJs as the backend language and sql server as the database. While I have managed to delete whole table rows from the database successfully, I am facing a challenge when it comes to deleting a specific row. Here is the ...

Is it possible for data transmitted or received through a socket written in various languages to be comprehended by both parties involved?

Is it possible for data to be transmitted accurately between two programs written in different languages (C++ and JavaScript using Node.js in this case) when connected through a socket? ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...