@keestalkstech/

RoundAffectionateCertifications

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// some sample data
let product = {
  "images": [{
    "file_name": "16241908_mb_01",
    "image_category": "mb"
  },
  {
    "file_name": "16241908_db_01",
    "image_category": "db"
  },
  {
    "file_name": "16241908_mb_02",
    "image_category": "mb"
  },
  {
    "file_name": "16241908_mb_03",
    "image_category": "mb"
  },
  {
    "file_name": "16241908_eb_01",
    "image_category": "eb"
  },
  {
    "file_name": "16241908_pb_01",
    "image_category": "pb"
  }]
};

console.log('completeProduct sort order:', product.images)

// `mb` preceeds `pb` images
const imageCategorySortOrder = ['mb', 'pb']
product.images.sort((a, b) => {

  // get the index
  let iA = imageCategorySortOrder.indexOf(a.image_category);
  let iB = imageCategorySortOrder.indexOf(b.image_category);

  // no index? put it in the back
  if (iA == -1) iA = imageCategorySortOrder.length;
  if (iB == -1) iB = imageCategorySortOrder.length;

  // indexes differ? Sort by index
  if (iA != iB) return iA < iB ? -1 : 1;

  // same index? sort alphabetically
  return a.file_name < b.file_name ? -1 : 1;
});

console.log('\nNew sort order:', product.images);
node v10.16.0