-4

I have an array that I get from an API. I need to sort the data based on the order value.

The data is kind of complex, here is an example:

const data = [{
  gallery: {
    id: 91,
    media: [{
      type: 'image',
      file: 'http://xxxxx.jpg', 
    }],
    title: 'title 3',
    description: 'test',
    order: 3,
    is_main: false,
    created_at: '2020-08-02T15:19:44.319133Z',
    updated_at: '2020-08-02T16:48:06.766478Z',
  }
},
{
  gallery: {
    id: 91,
    media: [{
      type: 'image',
      file: 'http://xxxxx.jpg', 
    }],
    title: 'title 2',
    description: 'test',
    order: 2,
    is_main: false,
    created_at: '2020-08-02T15:19:44.319133Z',
    updated_at: '2020-08-02T16:48:06.766478Z',
  }
}]

I need a way to sort the data based on the order given in the API.

0

2 Answers 2

-1

You could use the Array sort method with a comparator function to define the order.

In one-line:

data.sort((a, b) => a.gallery.order - b.gallery.order)

Here's a runnable example that logs the array after sorting:

const data = [{
  gallery: {
    id: 93,
    media: [{
      type: 'image3',
      file: 'http://xxxxx3.jpg',
    }],
    title: 'title 3',
    description: 'test3',
    order: 3,
    is_main: false,
    created_at: '2020-08-03T15:19:44.319133Z',
    updated_at: '2020-08-03T16:48:06.766478Z',
  }
}, {
  gallery: {
    id: 92,
    media: [{
      type: 'image2',
      file: 'http://xxxxx2.jpg',
    }],
    title: 'title 2',
    description: 'test2',
    order: 2,
    is_main: false,
    created_at: '2020-08-02T15:19:44.319133Z',
    updated_at: '2020-08-02T16:48:06.766478Z',
  }
}]

data.sort((a, b) => a.gallery.order - b.gallery.order)
console.log(data)

* Some small adjustments were made to the fields to make the differences more obvious for example purposes

Sign up to request clarification or add additional context in comments.

Comments

-2

You can use array.reduce to do a simple insertion sort.

let sorted = data.reduce((acc, next) => {
  acc[next.gallery.order] = next;
  return acc;
},[]);

If you have the need to avoid any empty indexes, you can filter undefined after the sort.

let sorted = data
  .reduce((acc, next) => {
    acc[next.gallery.order] = next;
    return acc;
  }, [])
  .filter((el) => el);

1 Comment

I am happy to help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.