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.

6
  • 1. What have you tried? 2. What should happen when the two elements have identical color properties? Commented Dec 6, 2016 at 12:10
  • Possible duplicate of Sort array of objects by string property value in JavaScript Commented Dec 6, 2016 at 12:10
  • @Andreas It's not a duplicate, because it's not alphabetical sorting. Commented Dec 6, 2016 at 12:11
  • any order in case duplicate is fine Commented Dec 6, 2016 at 12:11
  • like all green will come first then all yellow then red Commented Dec 6, 2016 at 12:12

1 Answer 1

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)

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

1 Comment

@NenadVracar if sort function return -ve then it swap and +ve then it don't swap ??

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.