Using Javascript to organize an array of objects based on a specific condition

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.

Answer №1

To find the index of a specific color and compare it, you can utilize the indexOf function.

let objects = [{'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 availableColors = ['red','blue']

objects.sort((a,b) => {
  let indexA = availableColors.indexOf(a.color);
  let indexB = availableColors.indexOf(b.color) ;
  return indexA === indexB ? a.position-b.position : indexA - indexB 
});

console.log(objects);

Answer №2

Here is a custom sorting algorithm:

const 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
  },
];

const result = obj.sort((a, b) => {
  if (a.color === b.color) {
    return a.position - b.position;
  } else return a.color - b.color;
});

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Using vue.js to compute properties for each object element

Vue.component ('app-mansion', { data: function () { return { message: 'Greetings, world', mansions: [ {name: "SKY8"}, {name: "SKY12"} ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

Utilizing the `theme` property in makeStyles with Material-UI

I am currently working on passing down an muiTheme to a component through the use of ThemeProvider, and I also want to apply it to the children components. Furthermore, I aim to utilize the theme's properties in both components by creating a classes o ...

The validation feature in ASP.NET MVC does not seem to be functioning properly while using

I'm struggling to make the bootstrap modal and asp.net mvc validation work together seamlessly. My form is quite complex with validation displayed in a bootstrap modal. However, when I press the submit button, the validation doesn't seem to be fu ...

jQuery problem: Unable to access a property that is undefined

After testing my code on JSfiddle, I noticed that it works perfectly. However, when I try to implement it on a webpage with jQuery already loaded in the DOM, I encounter a console error, shown in the screenshot. I am certain that the iframe selector I am ...

What are the top JavaScript widget libraries for a measurement reporting web application?

Embarking on a new venture to develop a web application tailored for engineers in need of reporting measurements. The key elements that form the backbone of this project include: grids charts maps After thorough research, I have delved into various java ...

Troubleshooting issues with AngularJS routing

Having trouble clicking on the show button and seeing anything displayed. I've spent a lot of time on this without success, can someone please assist. Files.... app.js controller.js index.html show.html index.html <html ng-app='Java4sApp& ...

Tips for displaying "No Results" without causing any lag in the browser

I'm encountering difficulty trying to implement a simple feature without resorting to a "messy" solution. The performance is suffering, and I am certain it's not done in a "professional" manner. What I desire is straightforward – displaying a ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

"An issue with Angular Http Get causing Status 0 to be consistently returned when using ng

I've been attempting to make this function properly. The concept is simple: click the tag, which then triggers a REST service call that returns a JSON result. I extract the country name from the response just for testing purposes. I'm currently u ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

Running Jest encounters errors when there is ES6 syntax present in the node modules of a create-react-app project

Currently, I am working on a project using create-react-app and attempting to perform unit testing on a component from office-ui-fabric-react using Jest and Enzyme. The most recent version of office-ui-fabric-react utilizes es6 syntax which is causing iss ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

Retrieving the values of multiple selected options from various select fields simultaneously

Picture having a dynamic number of select fields (the value of this variable is not fixed). I am looking to extract the values of the selected option from each select field using jQuery (or vanilla JavaScript). This is my approach: var cars = $(".sele ...

A continuous jQuery method for updating select option values

I'm currently working on a form and using jQuery to make some alterations. The form consists of multiple select elements, and I want to change the value of the first option in each of them. However, as the form allows for dynamic addition of new selec ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...

Connect tinyMCE to knockout.js

Learn how to utilize tinyMCE custom binding using. public sealed class CabinetShapeEditModel { public string Description { get; set; } } When implementing in the view: <script type="text/javascript"> var jso = @Html.Raw(Json.Encode ...