3

What I am trying to do is sort my three arrays (array1, array2, and array3) in order by their 0th term, to display the following.

1, banana, 2, grapes, 3, oranges.

This is my code, but I can't figure out how to get it to sort 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}));
}

2 Answers 2

3

Sort the elements 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]}));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Replace Your code with this :

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 Comment

Does not work for 1,3,21 gives output as 1,21,3 : jsfiddle.net/7frhj2dv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.