Sort an array of arrays based on the value of the second element in every inner array using JavaScript

Here is an array configuration I am working with:

const arr = [
  [500, 'Foo'],
  [600, 'bar'],
  [700, 'Baz'],
];

I am looking to reorganize this arr in alphabetical order based on the second element within each nested array, like so:

[
  [600, 'bar'],
  [700, 'Baz'],
  [500, 'Foo'],
]

It's important to note that the sorting should be case insensitive. Additionally, I'm open to using lodash utilities for assistance!

Answer №1

Below is a practical, live demonstration showcasing the usage of Array.prototype.sort:

const array = [
  [500, 'Apple'],
  [600, 'Banana'],
  [700, 'Cherry']
];

array.sort((x,y) => x[1].toUpperCase().localeCompare(y[1].toUpperCase()));

console.log(array);

Answer №2

When using Array.prototype.sort, a function is required to dictate how the items within the array are sorted. This function compares pairs of items and should return a positive number, 0, or a negative number based on their relationship.

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

Using AngularJS to display a targeted row in a table

I am currently working with a basic table and using ng-repeat to display rows in the table. I have a specific requirement where I want to show an additional row when a regular row is clicked. This additional row should contain custom markup in just one co ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...

Heroku causing issues with the functionality of my Rails and Angular.js application through the minification of JS files

I'm currently working on a new Rails 4.2.0 app with Angular.js deployed on Heroku. Here's the angular.js controller I've implemented: angular.module("CarDealer.controllers",[]).controller('carsController', function ($scope, carDea ...

What is the best way to prevent certain search terms from appearing in search results on my website's search form

Is there a way to prevent certain search terms from showing up in my search box? For example, how can I block the search query for "dog"? <form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech"> <input type="t ...

Is it possible to eliminate the border of an HTML element when clicked, while still keeping the border intact when the element is in

I am currently developing a project with an emphasis on Web accessibility. Snippet of Code: function removeBorder(){ li=document.getElementById("link"); li.classList.add(".remove") } body{ background:#dddddd; } p:focus{ border:1px solid red; } li{ ...

Try uploading a file with the imageUpload function in JavaScript, could be something basic

Today I successfully uploaded a picture using a basic button (id: "imageUpload") to select and upload a file. Everything worked flawlessly, with the thumbnail of the picture appearing in "thumb1." Now, I am attempting to allow users to upload a picture by ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Generate and display a random element on a webpage using Javascript or jQuery on page refresh

Currently, I am developing a website for my unique custom themes on a blogging platform. One of the features I am looking to add is a review section, where only one random review will display per page refresh. My question is, can anyone assist me in crea ...

Encountered a resource loading issue with a 500 error while utilizing jQuery in a Salesforce sidebar component

It is known that accessing custom labels in a sidebar component can be tricky. To overcome this limitation, I created a web service class in Apex that retrieves the custom label and utilized sforce.apex.execute to access it in a jQuery script. Initially, e ...

Remove an owl carousel using Laravel, Vue.js, and Axios

I've implemented a sleek slider on my website to showcase images with accompanying text to visitors. The slider utilizes owl carousel within a vue component and is functioning properly. Now, I'm attempting to add a delete button so that users who ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...

Using val() on a checkbox will give you an element, not a string literal

How can I retrieve only the literal values of all checked checkboxes without any additional data? My current approach is: $('input:checked').map(function() { return $(this).val(); }) The result that I am getting looks like this: e.fn.init[1]0 ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

Transferring the URL via AJAX

Trying to search for a user in the database using ajax. Upon successful retrieval, it should display a link with the username as the anchor text. Previously, everything was functioning properly without the link, but now it shows 'undefined'. Ackn ...

Tips for changing array items into an object using JavaScript

I am working with a list of arrays. let arr = ["one","two"] This is the code I am currently using: arr.map(item=>{ item }) I am trying to transform the array into an array of sub-arrays [ { "one": [{ ...

Contrast and showcase the discrepancy between two POJO objects in Java

In my project, I have a requirement to compare two Pojo objects and display the result. The scenario involves comparing a Db value with an input file. To handle this, I have created a POJO class named BuySellTO. POJO Class Structure: public class BuySel ...

Showing all elements on page load that are currently being filtered out in React

I've created a page that displays a grid of images with various details like title, description, author, and more. All this data is being pulled from my SQL table (referred to as marketplaceData). To enhance user experience, I added a search bar to f ...

Javascript - Spin the Wheel of Fortune

I am looking to create a wheel of fortune using JavaScript. My goal is to set both the output and starting position of the wheel. When the user spins the wheel at a minimum speed, it should rotate multiple times based on the speed before landing on the des ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...