How to sort arrays with multiple elements - Javascript
What I'm trying to do is sort my three arrays (array1, array2 and array3) in the order of their 0th member to display the following.
1, banana, 2, grapes, 3, oranges.
This is my code, but I can't figure out how to sort it the way I want.
var array1 = ["1", "banana"];
var array2 = ["3", "oranges"];
var array3 = ["2", "grapes"];
var array4 = [];
function myFunction(){
array4.push(array1, array2, array3);
alert((array4).sort(function(a, b){return a-b}));
}
+3
Thomas M
source
to share
2 answers
Sort items based on [0]
th index .
(array4).sort(function(a, b){return a[0]-b[0]})
function myFunction(){
array4.push(array1, array2, array3);
alert((array4).sort(function(a, b){return a[0]-b[0]}));
}
+3
Shaunak D
source
to share
Replace your code with the following:
var array1 = ["1", "banana"];
var array2 = ["3", "oranges"];
var array3 = ["2", "grapes"];
var array4 = [];
function myFunction()
{
array4.push(array1, array2, array3);
alert(array4.sort());
}
You output will be 1, banana, 2, grapes, 3, oranges
+1
David coder
source
to share