Steps for performing position by position sorting within an array of arrays of numbers using the Lodash library

My task involves sorting an array of strings:

['1.2.3', '1.5.2', '1.23', '1.20.31']

I am looking for a way to sort the array by splitting each string separated by dots, such as 1.2.3 into ['1','2', '3'], and then comparing them position by position similar to Python tuple comparison.

The expected result should be:

['1.2.3', '1.5.2' '1.20.31', '1.23']

I am aware that this can be achieved using native JavaScript's .sort method with a custom comparison function. However, I am unable to modify the original array. Is there a way to accomplish this using Lodash's _.sortBy which requires a key function?

Answer №1

Solution using Pure JavaScript:

var numbers = [100, 50, 25, 10];

function customSort(arr) {
    return arr.sort(function (a, b) {
        return a - b;
    });
}

document.write('<pre>sorted array ' + JSON.stringify(customSort(numbers), 0, 4) + '</pre>');
document.write('<pre>original array ' + JSON.stringify(numbers, 0, 4) + '</pre>');

Answer №2

If you need to perform advanced sorting operations, you can leverage the power of sortByAll(). Here's an example:

var elements = ['1.2.3', '1.5.2', '1.23', '1.20.31', '1.20.29'];

function extractNumber(segmentIndex, str) {
    return parseInt(_.get(str.split('.'), segmentIndex, 0));
}

_.sortByAll(
    elements,
    _.partial(extractNumber, 0),
    _.partial(extractNumber, 1),
    _.partial(extractNumber, 2)
);
// Result: ["1.2.3", "1.5.2", "1.20.29", "1.20.31", "1.23"]

The extractNumber() function retrieves the specific number segment from a string as an integer. Using partial(), we create the three iteratees required for sortByAll().

Answer №3

Using ES5 and Lodash Library

var numbers = ['1.2.3', '1.5.2', '1.23', '1.20.31'];
var sortedNumbers = _.sortBy(numbers, function(x){ return
                   x.split('.')
                    .map(function(i){ return 
                       _.padLeft(i, 5, '0'); })
                    .join('');
                 }));

Adopting ES6 with Lodash

var numbers = ['1.2.3', '1.5.2', '1.23', '1.20.31'];
var sorteddData = _.sortBy(numbers, x =>
                    x.split('.')
                     .map(i => _.padLeft(i, 5, '0'))
                     .join('')
                    );

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

Guide to selecting and clicking multiple elements with a specific class using jQuery

On my html page, I have the following elements: $(".pv-profile-section__card-action-bar").length 3 I want to click on all of these elements instead of just the first one. Currently, I am achieving this with the code: $(".pv-profile-section__card-action- ...

Navigating URLs to Single Page Application Routing in Vue.js

I'm new to using vue-router and I'm curious if there's a way to manage redirection in Vue or if there are alternative methods in a node.js environment. For instance, when someone tries to access my site by typing the URL example.com/contac ...

I'm new to learning JavaScript and I'm wondering how I can receive a single alert using only the if operator

Extracted from the book "Beginning JS 4th edition", this code snippet displays two alert messages when loaded in a browser due to two NaN entries in an array. To ensure that only one alert is shown every time, how can I achieve this using the if operator? ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

Enhance your website's accessibility by using JavaScript to allow the down and up arrow keys to function

Thank you for taking the time to read this, any feedback is greatly appreciated. The current script on my website is only partially functional (click "i" in the bottom right corner). Currently, the script will focus on the first link AFTER pressing the T ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

"Encountered an issue with ng-annotate during processing

I'm attempting to utilize ng-annotate on my Angular application, but it seems to be not working at all. Here is the configuration part: (function () { 'use strict'; angular.module('app') .config(/*@ngInject*/ ro ...

The webpage must be designed to be compatible with screen resolutions starting from 800 x 600 pixels and higher, utilizing Angular

I am working on developing a webpage that is specifically designed to work for resolutions of 800 x 600 pixels and higher. Any other resolutions will display the message "This website can only be accessed from desktops." Here is my approach using jQuery: ...

What is the process of generating a popup panel without relying on libraries, using JavaScript and CSS?

I'm currently working on creating a popup panel that is centered on the screen with rounded corners (scrollbars are unnecessary) using jQuery min, similar to this example: https://i.stack.imgur.com/0kYO6.png My progress so far: function (package) ...

Having difficulty with sending an AJAX GET request to connect to mongodb

I've been facing a challenging task of displaying data from a mongodb collection on the browser using nodejs and express. Here's the client-side call: document.onload= $(function (e) { var i = 0; $.ajax({ type: "GET", url: "http://localh ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

Storing information in an array based on a specific flag

Currently, I am developing an Angular application where I am dealing with a specific array that contains a flag named "checked". Based on the value of this flag, I need to perform certain manipulations. Here is a snippet of my sample data: const data = [{ ...

loading times of Bootstrap-select are slow when used in multiples

I am facing performance issues on my website when I try to include more than 20 select options. The jQuery execution slows down significantly and there is a stop/continue alert, taking minutes to load. Is there any way to optimize the code for faster loadi ...

The request body is not showing up as a key-value pair, while the request headers and other parameters are visible

Example of 'Advanced REST Client' Request I am currently using Postman and Advanced REST client to create a simple POST request based on the code below: 'use strict'; var express = require('express'); var bodyParser = requir ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...