Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript sort multidimensional array

let arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];

// sort by first column (numbers) using minus
arr.sort((a, b) => a[0]-b[0]);
/* [[12,"AAA"],[12,"BBB"],[12,"CCC"],[12,"DDD"],[18,"CCC"],[18,"CCC"],[28,"DDD"],[28,"DDD"],[28,"DDD"],[58,"BBB"],[68,"BBB"],[78,"BBB"]] */

// sort by second column (letters) using localeCompare
arr.sort((a, b) => a[1].localeCompare(b[1]));
/* VM704:1 [[12,"AAA"],[12,"BBB"],[58,"BBB"],[68,"BBB"],[78,"BBB"],[12,"CCC"],[18,"CCC"],[18,"CCC"],[12,"DDD"],[28,"DDD"],[28,"DDD"],[28,"DDD"]] */
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #javascript #sort #multidimensional #array
ADD COMMENT
Topic
Name
8+9 =