Barry Watts
Barry Watts

Reputation: 794

Rearrange two-dimensional array by array element

I have a 2D array that is structured like this:

image_arrary[[image1.jpg, 1][image2.jpg, 2][image3.jpg, 3]]

the inner array elements are image_name and image_order

The user can click a button which will change the order of the images so after a click the array looks like this

image_arrary[[image1.jpg, 1][image2.jpg, 3][image3.jpg, 2]]

How do I rearrange the array so that the array is ordered by the image_order so it looks like this?

image_arrary[[image1.jpg, 1][image3.jpg, 2][image2.jpg, 3]].

Many thanks in advance.

Upvotes: 1

Views: 250

Answers (2)

FixMaker
FixMaker

Reputation: 3877

Arrays in JavaScript have a sort() method that can take an optional parameter; this parameter is a function where you can define some custom comparison code that helps the sort() method determine which array element is the 'greater'. So, for your example, you could do something like this:

var inputArray = [
    ['image1.jpg', 1],
    ['image2.jpg', 3],
    ['image3.jpg', 2]
];

inputArray.sort(function(a, b) {
    return a[1] - b[1];
});

/* inputArray is now sorted /*

In this example the a and b parameters of the 'compare function' will be elements of your 'outer' array. Since you have an array of arrays, a and b will be arrays in the form ['image1.jpg', 1]. The compare function just checks the second element of these and returns true if the second element in a is less than the second element in b. This allows the sort() method to determine which 'sub-array' in the 'outer' array should come first.

You can see an example of it working here.

Upvotes: 1

Alex Funk
Alex Funk

Reputation: 435

You could do a simple sort:

image_array.sort(function(a, b) {
   return a[1] - b[1];
}) 

Upvotes: 2

Related Questions