Search code examples
javascriptarrayssortingjavascript-objects

Javascript sort an array of objects by comparing with a certain condition


I have an array of objects like this:

obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
        {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
        {'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
        {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
        {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3},
        {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}]

What I wish to achieve is, sort the array of objects in ascending order by position for all the objects with a similar color. My expected output is this:

 obj = [{'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
        {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
        {'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
        {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}
        {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
        {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3}]

My approach: I have the set of unique colors like this:

unique_colors = ['red', 'blue'];
for (var i in unique_colors){
  obj.forEach(function(x){
  if (i === x.colors){
  obj.sort((a,b) => a.position - b.position);
}
}
});

But that didn't work. Please assist me where I am going wrong. Thanks a lot in advance. Sorry if its trivial, am still learning javascript.


Solution

  • You can use indexOf function to get the index of the color and compare

    let objArr = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3},
            {'name': 'Sam', 'age': 19, 'gender': 'male', 'color':'red', 'position':2},
            {'name': 'Harry', 'age': 16, 'gender': 'male', 'color':'red', 'position':1},
            {'name': 'Charles', 'age': 19, 'gender': 'male', 'color':'blue', 'position':2},
            {'name': 'Fred', 'age': 21, 'gender': 'male', 'color':'blue', 'position':3},
            {'name': 'Mike', 'age': 23, 'gender': 'male', 'color':'blue', 'position':1}];
            
    let colors = ['red','blue']
    
    objArr.sort((a,b) => {
      let idxA = colors.indexOf(a.color);
      let idxB = colors.indexOf(b.color) ;
      return idxA === idxB ? a.position-b.position : idxA - idxB 
    });
    
    console.log(objArr);