Home > Web Front-end > JS Tutorial > How Can You Sort a Two-Dimensional Array by Column Value in JavaScript?

How Can You Sort a Two-Dimensional Array by Column Value in JavaScript?

Mary-Kate Olsen
Release: 2024-11-17 04:22:03
Original
166 people have browsed it

How Can You Sort a Two-Dimensional Array by Column Value in JavaScript?

Sorting Two-Dimensional Arrays by Column Values in JavaScript

In this article, we will explore how to sort a two-dimensional array in JavaScript by a specific column value.

Problem Statement

Given a two-dimensional array represented as an array of arrays, each sub-array containing two elements, the task is to sort the array in ascending order based on the values in the first column (column with index 0).

Solution

JavaScript provides a convenient method, sort(), that can be utilized to sort multidimensional arrays. Let's break down the provided code:

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];

a.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}
Copy after login

Explanation

  • The sort() method is invoked on the a array.
  • The sortFunction is passed as the argument to the sort() method. This function compares two sub-arrays' first elements (a[0] and b[0]) and returns:

    • 0 if they are equal.
    • -1 if a[0] is less than b[0].
    • 1 if a[0] is greater than b[0].

By default, sort() uses the returned values to determine the ordering of the sub-arrays, sorting them in ascending order.

Sorting By Second Column

To sort by the second column, the sortFunction can be modified to compare second column values:

a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}
Copy after login

This enables flexibility in sorting by different columns based on the specific requirements.

The above is the detailed content of How Can You Sort a Two-Dimensional Array by Column Value in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template