Sort Multidimensional Array by Multiple Columns

Sort multidimensional array by multiple columns

You need array_multisort

$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);

# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);

As of PHP 5.5.0:

array_multisort(array_column($mylist, 'event_type'), SORT_DESC,
array_column($mylist, 'title'), SORT_ASC,
$mylist);

$mylist is now:

array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)

How does one sort a multi dimensional array by multiple columns in JavaScript?

The array literal [] is preferred over new Array. The notation {0,4,3,1} is not valid and should be [0,4,3,1].

Is there a need for reinventing the wheel? Two arrays can be joined using:

originalArray = originalArray.concat(addArray);

Elements can be appended to the end using:

array.push(element);

Arrays have a method for sorting the array. By default, it's sorted numerically:

// sort elements numerically
var array = [1, 3, 2];
array.sort(); // array becomes [1, 2, 3]

Arrays can be reversed as well. Continuing the previous example:

array = array.reverse(); //yields [3, 2, 1]

To provide custom sorting, you can pass the optional function argument to array.sort():

array = [];
array[0] = [1, "first element"];
array[1] = [3, "second element"];
array[2] = [2, "third element"];
array.sort(function (element_a, element_b) {
return element_a[0] - element_b[0];
});
/** array becomes (in order):
* [1, "first element"]
* [2, "third element"]
* [3, "second element"]
*/

Elements will retain their position if the element equals an other element. Using this, you can combine multiple sorting algoritms. You must apply your sorting preferences in reverse order since the last sort has priority over previous ones. To sort the below array by the first column (descending order) and then the second column (ascending order):

array = [];
array.push([1, 2, 4]);
array.push([1, 3, 3]);
array.push([2, 1, 3]);
array.push([1, 2, 3]);
// sort on second column
array.sort(function (element_a, element_b) {
return element_a[1] - element_b[1];
});
// sort on first column, reverse sort
array.sort(function (element_a, element_b) {
return element_b[0] - element_a[0];
});
/** result (note, 3rd column is not sorted, so the order of row 2+3 is preserved)
* [2, 1, 3]
* [1, 2, 4] (row 2)
* [1, 2, 3] (row 3)
* [1, 3, 3]
*/

To sort latin strings (i.e. English, German, Dutch), use String.localeCompare:

array.sort(function (element_a, element_b) {
return element_a.localeCompare(element_b);
});

To sort date's from the Date object, use their milliseconds representation:

array.sort(function (element_a, element_b) {
return element_a.getTime() - element_b.getTime();
});

You could apply this sort function to all kind of data, just follow the rules:

x is the result from comparing two values which should be returned by a function passed to array.sort.

  1. x < 0: element_a should come before element_b
  2. x = 0: element_a and element_b are equal, the elements are not swapped
  3. x > 0: element_a should come after element_b

Sort multidimensional array by multiple fields

What you want is to sort the users based on the lowest index of their titles in $order. You could make use of array_search to find each of their titles' index in $order and find the lowest number using min. If they're the same, fall back to strcmp.

usort($users, function($a, $b) use ($order) {
$minAPos = min(array_map(function($title) use ($order) {
$pos = array_search($title, $order);
return $pos === false? sizeof($order) : $pos;
}, $a['titles']));
$minBPos = min(array_map(function($title) use ($order) {
$pos = array_search($title, $order);
return $pos === false? sizeof($order) : $pos;
}, $b['titles']));

if($minAPos === $minBPos) {
return strcmp($a['lastName'], $b['lastName']);
} else {
return $minAPos <=> $minBPos;
}
});

How to sort multiple columns data in Multi-Dimensional array?

I also face the same issue and found a good solution for sort multiple columns data in Multi-Dimensional array.

Check the below code

(function() {      function deepsort(){    var i, order= arguments, L= order.length, tem;    return a.sort(function(a, b){        i= 0;              while(i < L){                      tem= order[i++];          var res = tem.split("_");            var ao= a[res[0]] || 0, bo= b[res[0]] || 0;            if(ao== bo) continue;                     if(res[1] == "ASC"){            return ao > bo? 1: -1;          }          if(res[1] == "DESC"){             return ao < bo? 1: -1;          }        }        return 0;    });}
var a= [ ["2015-08-09", 1.2, 1.20, 2.1], ["2015-08-10", 1.2, 1.21, 2.11], ["2015-08-11", 1.2, 0.99, 2.20], ["2015-10-29", 1.2, 1.12, 2.22], ["2015-09-10", 1.21, 1.19, 2.00]];document.write(deepsort(1+"_ASC",2+"_ASC"));// for better result view check console logconsole.log(deepsort(1+"_ASC",2+"_ASC"))//console.log(a.deepsort(1)) })();

C# sorting multidimensional array by multiple columns

Use a List<> object with Linq

using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace ConsoleApplication19{ class Program { static void Main(string[] args) { List<List<int>> multiarray = new List<List<int>>{ new List<int> { 8, 63 }, new List<int> { 4, 2 }, new List<int> { 0, -55 }, new List<int> { 8, 57 }, new List<int> { 2, -120}, new List<int> { 8, 53 } };
List<List<int>> sortedList = multiarray.OrderBy(x => x[1]).OrderBy(y => y[0]).ToList();
} }}

PHP Sort Multidimensional Array Based on Multiple Criteria

I found a solution that uses array_multisort()

foreach ($arr as $key => $row) {
$wins[$key] = $row[1];
$losses[$key] = $row[2];
$ptsfor[$key] = $row[3];
}
array_multisort($wins, SORT_DESC, $losses, SORT_ASC, $ptsfor, SORT_DESC, $arr);

Sort an array of associative arrays by multiple columns using a combination of ascending, descending, regular, numeric, and natural sorting

I think you have to implement a custom comparison function for this behavior:

function myCmp($a, $b) {
$nameCmp = strnatcasecmp($a['Name'], $b['Name']);
$ageCmp = strnatcasecmp($a['Age'], $b['Age']);
$codeCmp = strnatcasecmp($a['Code'], $b['Code']);

if ($nameCmp != 0) // Names are not equal
return($nameCmp);

// Names are equal, let's compare age

if ($ageCmp != 0) // Age is not equal
return($ageCmp * -1); // Invert it since you want DESC

// Ages are equal, we don't need to compare code, just return the comparison result
return($codeCmp);
}

Then you can call usort($array, 'myCmp'); and should get the desired sorting

How to sort a multidimensional array by multiple columns?

Fundamentally we're going to use the same approach as explained here, we're just going to do it with a variable number of keys:

/**
* Returns a comparison function to sort by $cmp
* over multiple keys. First argument is the comparison
* function, all following arguments are the keys to
* sort by.
*/
function createMultiKeyCmpFunc($cmp, $key /* , keys... */) {
$keys = func_get_args();
array_shift($keys);

return function (array $a, array $b) use ($cmp, $keys) {
return array_reduce($keys, function ($result, $key) use ($cmp, $a, $b) {
return $result ?: call_user_func($cmp, $a[$key], $b[$key]);
});
};
}

usort($array, createMultiKeyCmpFunc('strcmp', 'foo', 'bar', 'baz'));
// or
usort($array, createMultiKeyCmpFunc(function ($a, $b) { return $a - $b; }, 'foo', 'bar', 'baz'));

That's about equivalent to an SQL ORDER BY foo, bar, baz.

If of course each key requires a different kind of comparison logic and you cannot use a general strcmp or - for all keys, you're back to the same code as explained here.

How to sort multidimensional array by multiple column index

You can do:

const sortCompareFn = sortArr => (a, b) => {
const getValue = v => sortArr.reduce((a, c) => a + v[c], '')
const aValue = getValue(a)
const bValue = getValue(b)
return typeof aValue === 'string'
? aValue.localeCompare(bValue)
: aValue - bValue
}

const source = [
["Jack","A","B1", 4],
["AVicky","M", "B2", 2],
["AVicky","F", "B3", 3],
]

const sortArr1 = [1]
const result1 = source.sort(sortCompareFn(sortArr1))
console.log('result1:', result1)

const sortArr23 = [2, 3]
const result23 = source.sort(sortCompareFn(sortArr23))
console.log('result23:', result23)

const sortArr3 = [3]
const result3 = source.sort(sortCompareFn(sortArr3))
console.log('result3:', result3)
.as-console-wrapper { max-height: 100% !important; top: 0; }


Related Topics



Leave a reply



Submit