Having an array of objects structured as follows:
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}]
The goal is to sort the objects in ascending order by position for each color. The expected output should be:
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}]
Attempted approach:
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);
}
}
});
It didn't yield the desired results. Seeking assistance and guidance to rectify the issue. Thank you for your help. I'm still learning Javascript.