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

What methods are available for implementing hover effects within attributes using a JavaScript object?

const customPanelStyle = { 'background-color': 'red', 'border': '1px solid green', ':hover'{ 'background': 'blue' } } class some extends React.Component{ rende ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

Utilize jQuery for parsing JSON data

Asking for help here because I am struggling with a seemingly simple task. Here is the JSON data that's causing me trouble: {"name":"cust_num","comparison":"starts_with","value":"01"}, {"name":"cust_name","comparison":"starts_with","value":"ad"}, {"n ...

When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not! var url = './images/pros/imagefile.png'; var http = new XMLHttpRequest(); http.o ...

Encountering errors with passport-google-oauth20: InternalOAuthError arises when fetching user profile fails and attempting to set headers after they have already been sent to the client

When using passport strategies for various social media logins, I encountered the following two errors: InternalOAuthError: Failed to fetch user profile Cannot set headers after they are sent to the client I suspect that I may have returned a callback or ...

Is it possible to use the Husky "commit-msg" hook to git add new files?

I am currently setting up an automatic versioning system where if I use git commit with the message format PATCH: {message}, the app's patch version will automatically be updated (and the same for the prefixes MINOR and MAJOR as well). My approach inv ...

Firebase will automatically log users out after one hour of inactivity

After conducting thorough research, I have learned that Firebase updates a refresh token every hour because Firebase ID tokens expire after one hour. It is mentioned that the automatic refreshing of tokens by Firebase occurs without any action required fro ...

An error is thrown when using AngularJS .length property

Currently, I am carrying out a regular task within my Filter to verify if angular.module('someApp') .filter('filterSomeData',['$filter',function ($filter) { return function (items, keyObj) { var filterObj ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

What methods are most effective for verifying user credentials in a web application using Node.js and AngularJS?

Currently, I am working on a project that involves using Node.js and MySQL for handling user data. I would like to leverage the user information stored in the MySQL database, but I am unsure about the most secure method for implementing user authentication ...

having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't. <script> let myBtn = document.querySele ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Is there a way to seamlessly transition between images in a slider every 3 seconds using javascript?

<!DOCTYPE html> <html> <head> <title>Hello</title> <meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/> <style> *{margin:0; padding:0;} .mySlides{ position:relative; width:1000px; ...

Tips for obtaining user input to place markers on a video timeline with JavaScript

I am new to Java script and I am trying to create a video player where users can click on the progress bar to place markers. Can you please review my code below and let me know if there are any errors? index.html <!doctype html> <html> <he ...

Ways to ensure the text on my website scrolls into view as the user navig

Is there a way to have my text show up as I scroll? I came across this , but I'm interested in how it actually functions. I saw a similar inquiry before, but it doesn't make sense to me. Can someone please explain or provide some examples on how ...

What is the best way to implement variable scope when using a callback function in AngularJS

I'm facing a major issue in my AngularJS application. I have a factory module with an getAll() function that retrieves JSON data from the server. In the controller module, I attempt to assign the value returned by the factory's getAll() function ...

A see-through object appears only properly when viewed from one specific angle

I am currently working with THREE.js and the WebGL renderer, facing an issue with a self-transparent object in my scene. This object is composed of a single geometry with a basic material that includes a texture and has the transparent: true property enabl ...