1

I have array of object like :

var array = [
    { id: 1, color: red,    value: 1 },
    { id: 2, color: red,    value: 2 },
    { id: 3, color: yellow, value: 3 },
    { id: 4, color: yellow, value: 4 },
    { id: 5, color: green,  value: 4 }
];

I want sorted order where green -> yellow -> red

after array.sort(custmeSort()) output should be

[
    { id: 5, color: green,  value: 4 },   
    { id: 3, color: yellow, value: 3 },
    { id: 4, color: yellow, value: 4 },
    { id: 1, color: red,    value: 1 },
    { id: 2, color: red,    value: 2 }
]

How to achive this in javascript.

nozzleman
  • 9,529
  • 4
  • 37
  • 58
Arun Tyagi
  • 2,206
  • 5
  • 24
  • 37

1 Answers1

6

You can use one object to set sorting order, and then just use sort()

var array = [
  {id: 1, color: 'red',value: 1},
  {id: 2, color: 'red',value: 2},
  {id: 3, color: 'yellow',value: 3},
  {id: 4, color: 'yellow',value: 4},
  {id: 5, color: 'green',value: 4},
]
var order = {
  green: 1,
  yellow: 2, 
  red: 3
}

var result = array.sort(function(a, b) {
  return order[a.color] - order[b.color];
})

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • @NenadVracar if sort function return -ve then it swap and +ve then it don't swap ?? – Mahi Dec 06 '16 at 12:19